forked from WikiDeck/wikideck
Play: lobby leaderboards (mode players, network hosts); compact phone dock
Host credit per #6: hosted modes show their top players and the network's host leaderboard (matches hosted). Same-origin GETs, strings capped and rendered as text. On phones the lobby actions fit one row. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,49 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { Server, Trophy } from 'lucide-react';
|
||||||
|
import type { GameMode } from './types.ts';
|
||||||
|
|
||||||
|
// Host credit (modes, #6): per-mode player leaderboard and the network's host leaderboard.
|
||||||
|
// Same-origin GETs only; every string is untrusted and rendered as text.
|
||||||
|
type Entry = { name: string; wins: number; losses: number; draws: number; played: number };
|
||||||
|
type Host = { operator: string; matchesHosted: number; playersOnline: number; self: boolean; reachable: boolean };
|
||||||
|
const str = (v: unknown, max = 40) => (typeof v === 'string' ? v.slice(0, max) : '');
|
||||||
|
const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : 0);
|
||||||
|
const rows = (v: unknown, key: string): Record<string, unknown>[] => {
|
||||||
|
const list = v && typeof v === 'object' ? (v as Record<string, unknown>)[key] : undefined;
|
||||||
|
return Array.isArray(list) ? list.filter((x): x is Record<string, unknown> => !!x && typeof x === 'object').slice(0, 10) : [];
|
||||||
|
};
|
||||||
|
const get = (path: string) => fetch(path, { cache: 'no-store', signal: AbortSignal.timeout(8000) })
|
||||||
|
.then(r => (r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error('unavailable'))));
|
||||||
|
|
||||||
|
export function parseLeaderboard(v: unknown): Entry[] {
|
||||||
|
return rows(v, 'entries').map(e => ({ name: str(e.name, 24) || 'Anonymous', wins: num(e.wins), losses: num(e.losses), draws: num(e.draws), played: num(e.played) }));
|
||||||
|
}
|
||||||
|
export function parseHosts(v: unknown): Host[] {
|
||||||
|
return rows(v, 'hosts').map(h => ({ operator: str(h.operator, 60) || str(h.origin, 60) || 'unknown host', matchesHosted: num(h.matchesHosted),
|
||||||
|
playersOnline: num(h.playersOnline), self: h.self === true, reachable: h.reachable !== false }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Leaderboards({ mode }: { mode: GameMode }) {
|
||||||
|
const [players, setPlayers] = useState<Entry[]>();
|
||||||
|
const [hosts, setHosts] = useState<Host[]>();
|
||||||
|
const hosted = mode.host.kind === 'peer' && mode.host.self;
|
||||||
|
const remoteId = mode.remoteId;
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
get('/api/game/hosts/leaderboard').then(d => { if (active) setHosts(parseHosts(d)); }, () => { if (active) setHosts([]); });
|
||||||
|
if (hosted && remoteId) get(`/api/game/modes/${encodeURIComponent(remoteId)}/leaderboard`)
|
||||||
|
.then(d => { if (active) setPlayers(parseLeaderboard(d)); }, () => { if (active) setPlayers([]); });
|
||||||
|
else setPlayers(undefined);
|
||||||
|
return () => { active = false; };
|
||||||
|
}, [hosted, remoteId]);
|
||||||
|
if (!hosts?.length && !players?.length) return null;
|
||||||
|
return <details className="leaderboards">
|
||||||
|
<summary><Trophy size={14} /> Leaderboards</summary>
|
||||||
|
{players && <><h4>{mode.name}: top players</h4>{players.length
|
||||||
|
? <ol className="board-list">{players.map((p, i) => <li key={i}><span>{p.name}</span><b>{p.wins}W</b><small>{p.losses}L · {p.draws}D</small></li>)}</ol>
|
||||||
|
: <p className="muted small">No finished matches yet. Be the first.</p>}</>}
|
||||||
|
{!!hosts?.length && <><h4><Server size={13} /> Top hosts · matches hosted</h4>
|
||||||
|
<ol className="board-list">{hosts.map((h, i) => <li key={i} className={h.self ? 'self' : ''}><span>{h.operator}{h.self ? ' (this node)' : ''}{h.reachable ? '' : ' · offline'}</span><b>{h.matchesHosted}</b><small>{h.playersOnline} online</small></li>)}</ol>
|
||||||
|
<p className="muted small">Run a WikiDeck node and host your own modes to appear here.</p></>}
|
||||||
|
</details>;
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import { BOTS, type Bot } from './bots.ts';
|
|||||||
import { DEFAULT_STARTER, STARTERS, cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from './cards.ts';
|
import { DEFAULT_STARTER, STARTERS, cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from './cards.ts';
|
||||||
import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
|
import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
|
||||||
import { CategoryIcon } from './GameCard.tsx';
|
import { CategoryIcon } from './GameCard.tsx';
|
||||||
|
import { Leaderboards } from './Leaderboards.tsx';
|
||||||
import { MatchScreen } from './MatchScreen.tsx';
|
import { MatchScreen } from './MatchScreen.tsx';
|
||||||
import { lobbyName } from './online.ts';
|
import { lobbyName } from './online.ts';
|
||||||
import { OnlinePlay } from './OnlinePlay.tsx';
|
import { OnlinePlay } from './OnlinePlay.tsx';
|
||||||
@@ -91,11 +92,12 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
|
|||||||
{status === 'loading' && <p className="muted small"><Globe2 size={13} /> Looking for peer-hosted modes…</p>}
|
{status === 'loading' && <p className="muted small"><Globe2 size={13} /> Looking for peer-hosted modes…</p>}
|
||||||
{status === 'unavailable' && <p className="muted small"><Globe2 size={13} /> No peer-hosted modes reachable from this node.</p>}
|
{status === 'unavailable' && <p className="muted small"><Globe2 size={13} /> No peer-hosted modes reachable from this node.</p>}
|
||||||
</div>
|
</div>
|
||||||
|
{status === 'ok' && <Leaderboards key={mode.id} mode={mode} />}
|
||||||
|
|
||||||
{remote ? <>
|
{remote ? <>
|
||||||
<p className="muted small">This mode runs on {remote.name}’s node. Open it there to play; your eom.dev account works on every node.</p>
|
<p className="muted small">This mode runs on {remote.name}’s node. Open it there to play; your eom.dev account works on every node.</p>
|
||||||
<div className="play-dock"><div className="play-actions">
|
<div className="play-dock"><div className="play-actions">
|
||||||
<button className="button outline" onClick={() => setScreen('tutorial')}><CircleHelp size={16} /> How to play</button>
|
<button className="button outline" aria-label="How to play" onClick={() => setScreen('tutorial')}><CircleHelp size={16} /><span className="hide-narrow">How to play</span></button>
|
||||||
{remote.url ? <a className="button dark play-cta" href={remote.url} target="_blank" rel="noopener noreferrer">Play on {remote.name} <ExternalLink size={16} /></a>
|
{remote.url ? <a className="button dark play-cta" href={remote.url} target="_blank" rel="noopener noreferrer">Play on {remote.name} <ExternalLink size={16} /></a>
|
||||||
: <button className="button dark play-cta" disabled>Host address unavailable</button>}
|
: <button className="button dark play-cta" disabled>Host address unavailable</button>}
|
||||||
</div></div>
|
</div></div>
|
||||||
@@ -117,9 +119,9 @@ export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
|
|||||||
: warning && <p className="deck-warning small">{warning}</p>}
|
: warning && <p className="deck-warning small">{warning}</p>}
|
||||||
|
|
||||||
<div className="play-dock"><div className="play-actions">
|
<div className="play-dock"><div className="play-actions">
|
||||||
<button className="button outline" onClick={() => setScreen('tutorial')}><CircleHelp size={16} /> How to play</button>
|
<button className="button outline" aria-label="How to play" onClick={() => setScreen('tutorial')}><CircleHelp size={16} /><span className="hide-narrow">How to play</span></button>
|
||||||
{hosted && <button className="button outline" onClick={() => { setLastOnline(true); setScreen('online'); }}><Users size={16} /> Play a person</button>}
|
{hosted && <button className="button outline" aria-label="Play a person online" onClick={() => { setLastOnline(true); setScreen('online'); }}><Users size={16} /><span className="hide-narrow">Play a person</span><span className="show-narrow">Online</span></button>}
|
||||||
<button className="button dark play-cta" disabled={!!problem} onClick={start}><Play size={16} /> Play vs {bot.name}</button>
|
<button className="button dark play-cta" aria-label={`Play vs ${bot.name}`} disabled={!!problem} onClick={start}><Play size={16} /><span className="hide-narrow">Play vs {bot.name}</span><span className="show-narrow">Play</span></button>
|
||||||
</div></div>
|
</div></div>
|
||||||
</>}
|
</>}
|
||||||
</section>;
|
</section>;
|
||||||
|
|||||||
@@ -193,3 +193,15 @@ html.wd-in-match .auth-wrap,body:has(.match) .auth-wrap{display:none}
|
|||||||
/* Phones: on the Play route, hide the node/RPC chrome above the game so Play starts above the fold. */
|
/* Phones: on the Play route, hide the node/RPC chrome above the game so Play starts above the fold. */
|
||||||
@media(max-width:760px){html.wd-play .testnet-status,html.wd-play .error-banner,html.wd-play main>footer{display:none}}
|
@media(max-width:760px){html.wd-play .testnet-status,html.wd-play .error-banner,html.wd-play main>footer{display:none}}
|
||||||
@media(max-width:480px){html.wd-play:not(.wd-in-match) .play-dock{padding-right:62px}}
|
@media(max-width:480px){html.wd-play:not(.wd-in-match) .play-dock{padding-right:62px}}
|
||||||
|
.leaderboards{margin:12px 0 0;padding:10px 12px;border:1px solid var(--theme-border);border-radius:10px;background:var(--ctp-base)}
|
||||||
|
.leaderboards summary{cursor:pointer;display:flex;align-items:center;gap:6px;font-weight:700;font-size:13px;min-height:32px}
|
||||||
|
.leaderboards h4{font-size:12px;margin:10px 0 6px;display:flex;align-items:center;gap:5px;color:var(--ctp-subtext1)}
|
||||||
|
.board-list{list-style:none;padding:0;margin:0;display:grid;gap:4px;counter-reset:rank}
|
||||||
|
.board-list li{display:grid;grid-template-columns:22px 1fr auto auto;gap:8px;align-items:baseline;font-size:13px;counter-increment:rank}
|
||||||
|
.board-list li::before{content:counter(rank);color:var(--ctp-overlay1);font-size:11px}
|
||||||
|
.board-list li span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
|
.board-list li small{color:var(--ctp-subtext0);font-size:11px}
|
||||||
|
.board-list li.self span{color:var(--theme-accent)}
|
||||||
|
@media(max-width:480px){.hide-narrow{display:none}.play-actions{flex-wrap:nowrap}.play-actions .button{padding-inline:12px}}
|
||||||
|
.show-narrow{display:none}
|
||||||
|
@media(max-width:480px){.show-narrow{display:inline}.play-actions .button{min-width:0}}
|
||||||
|
|||||||
@@ -115,3 +115,14 @@ test('bots get only the hidden-information view, never the full match state', ()
|
|||||||
assert.ok(!json.includes('"rng"') && !json.includes('"seed"'), 'no RNG state or seed');
|
assert.ok(!json.includes('"rng"') && !json.includes('"seed"'), 'no RNG state or seed');
|
||||||
assert.ok(!('deck' in (v.engine!.view as object)), 'no deck order');
|
assert.ok(!('deck' in (v.engine!.view as object)), 'no deck order');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('leaderboard parsers cap and sanitise host data', async () => {
|
||||||
|
const { parseHosts, parseLeaderboard } = await import('../src/game/Leaderboards.tsx');
|
||||||
|
const hosts = parseHosts({ hosts: [{ operator: 'x'.repeat(200), matchesHosted: 5, playersOnline: -3, self: true }, null, 'junk', ...Array(20).fill({ origin: 'http://n' })] });
|
||||||
|
assert.equal(hosts.length, 10);
|
||||||
|
assert.equal(hosts[0].operator.length, 60);
|
||||||
|
assert.equal(hosts[0].playersOnline, 0);
|
||||||
|
assert.equal(hosts[1].operator, 'http://n');
|
||||||
|
assert.deepEqual(parseLeaderboard({ entries: [{ name: '', wins: 2 }] }), [{ name: 'Anonymous', wins: 2, losses: 0, draws: 0, played: 0 }]);
|
||||||
|
assert.deepEqual(parseLeaderboard(42), []);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user