forked from WikiDeck/wikideck
Merge pull request '[ui-pvp] PvP-first Play: owned-card eligibility, deck picker, quick match/invites, ladder, battle recap page (#65)' (#76) from night2/ui-pvp/collection-lobby into night/2026-11-17
This commit was merged in pull request #76.
This commit is contained in:
+17
-2
@@ -15,6 +15,9 @@ import { TradeDesk } from './TradeDesk.tsx';
|
||||
import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/network.ts';
|
||||
import { StateClient } from '../shared/rpc-client.ts';
|
||||
import { PlaySection } from './game/PlaySection.tsx';
|
||||
import { inviteFromPath } from './game/online.ts';
|
||||
import { BattleRecap, matchIdFromPath } from './game/recap/BattleRecap.tsx';
|
||||
import './game/recap/recap.css';
|
||||
import { isNativeApp } from './native.ts';
|
||||
import { Landing } from './Landing.tsx';
|
||||
import './App.css';
|
||||
@@ -47,8 +50,18 @@ function transferProblem(state: TestnetSnapshot, card: CardData, address: string
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [view, setView] = useState<View>('Discover');
|
||||
// Deep links (Night 2, ui-pvp): /play/invite/<code> opens Play with the invite; /recap/<id> (or /battle/<id>) is a recap page.
|
||||
const [invite] = useState(() => inviteFromPath(location.pathname));
|
||||
const [battle, setBattle] = useState(() => matchIdFromPath(location.pathname));
|
||||
const [view, setView] = useState<View>(() => (invite ? 'Play' : 'Discover'));
|
||||
const linkedAccount = useAccount();
|
||||
const openRecap = (id: string) => { history.pushState(null, '', `/recap/${encodeURIComponent(id)}`); setBattle(id); };
|
||||
const closeRecap = () => { history.pushState(null, '', '/'); setBattle(''); };
|
||||
useEffect(() => {
|
||||
const pop = () => setBattle(matchIdFromPath(location.pathname));
|
||||
window.addEventListener('popstate', pop);
|
||||
return () => window.removeEventListener('popstate', pop);
|
||||
}, []);
|
||||
const [wallet, setWallet] = useState<Wallet>();
|
||||
const [snapshot, setSnapshot] = useState<TestnetSnapshot>();
|
||||
const [rpcAvailable, setRpcAvailable] = useState(false);
|
||||
@@ -165,6 +178,8 @@ export default function App() {
|
||||
catch (e) { setError(message(e)); }
|
||||
};
|
||||
|
||||
// /recap/<id>: a standalone, shareable recap page (no hero or mining panel around it).
|
||||
if (battle) return <main className="recap-shell"><BattleRecap key={battle} matchId={battle} onExit={closeRecap} /></main>;
|
||||
return <div className="app-shell">
|
||||
<aside className="sidebar">
|
||||
<a href="#" className="brand" onClick={e => { e.preventDefault(); setView('Discover'); }}><span className="brand-mark" aria-hidden="true">W<span>✦</span></span>wikideck<span className="brand-dot">.</span></a>
|
||||
@@ -204,7 +219,7 @@ export default function App() {
|
||||
<article><ArrowLeftRight size={22}/><div className="section-eyebrow">TRADE · PLAYER TO PLAYER</div><h2>Swap cards directly.</h2><p>Prepare a signed offer for another collector and exchange card bundles atomically when the trade is mined. No prices or checkout.</p><button className="text-button" onClick={()=>setView('Trade cards')}>Trade cards <ArrowRight size={14}/></button></article>
|
||||
</section>
|
||||
</>}
|
||||
{view === 'Play' ? <PlaySection owned={owned} /> : view === 'Trade cards' ? <TradeDesk wallet={wallet} snapshot={snapshot} rpcAvailable={rpcAvailable} onNotice={setToast} /> : view !== 'Block explorer' ? <section className="discover-section">
|
||||
{view === 'Play' ? <PlaySection owned={owned} onMine={goMine} invite={invite} onRecap={openRecap} /> : view === 'Trade cards' ? <TradeDesk wallet={wallet} snapshot={snapshot} rpcAvailable={rpcAvailable} onNotice={setToast} /> : view !== 'Block explorer' ? <section className="discover-section">
|
||||
<div className="section-heading"><div><div className="section-eyebrow">{view === 'My collection' ? 'YOUR PERSONAL ENCYCLOPEDIA' : 'AN ENCYCLOPEDIA, REIMAGINED'}</div><h2>{view === 'My collection' ? 'Your cabinet of curiosities' : 'A world of possible discoveries'}<span className="count-badge">{visibleCards.length}</span></h2><p>{view === 'My collection' ? 'Confirmed native NFT ownership. Pending transfers stay here until mined.' : snapshot?.blocks.length ? 'Recent native NFTs on this node’s canonical chain.' : 'Sample previews only; mined NFTs use random Wikipedia pages with pictures. The same page may be minted more than once.'}</p></div>{view === 'Discover' && <button className="text-button" onClick={() => setView('My collection')}>My collection <ArrowRight size={16} /></button>}</div>
|
||||
<div className="filter-bar"><div className="category-tabs">{['All cards', 'Nature', 'Space', 'Science', 'People', 'History', 'Culture'].map(c => <button key={c} className={category === c ? 'selected' : ''} onClick={() => setCategory(c)}>{c}</button>)}</div><label className="search-input"><Search size={15} /><input aria-label="Search cards" placeholder="Find a discovery…" value={query} onChange={e => setQuery(e.target.value)} /></label></div>
|
||||
{filtered.length ? <div className="card-grid">{filtered.map(c => <div className="card-wrap" key={c.block?.tokenId ?? c.hash}><Card card={c} onClick={() => { setSelected(c); setTransferError(''); }} /><div className="card-list-caption"><span>{c.block ? `Block #${c.block.height}` : 'Example discovery'}</span><span className="caption-dot" />{c.block && snapshot ? short(testnetOwnerOf(snapshot, c.block.tokenId) ?? '') : 'Not owned'}</div>{c.block && snapshot?.pendingTransfers.some(tx => transactionCardIds(tx).includes(c.block!.tokenId)) && <span className="pending-label">Transfer or trade pending mining</span>}</div>)}</div> : <div className="empty-state"><img className="empty-state-logo" src="/original-logo.svg" alt="Wikideck" /><h3>{query || category !== 'All cards' ? 'No discoveries here. Yet.' : 'Your first discovery is waiting.'}</h3><p>{query || category !== 'All cards' ? 'Try another search or explore a different category.' : 'Use the native miner or receive a mined transfer on this chain. Restore a backup to access an existing wallet.'}</p><button className="button dark" onClick={goMine}><Pickaxe size={16} /> Explore native mining</button></div>}
|
||||
|
||||
@@ -43,6 +43,9 @@ export function account(): Account | undefined {
|
||||
return current?.account;
|
||||
}
|
||||
|
||||
/** The current Dex ID token, for same-origin game API calls (seats and collection, Night 2); undefined when logged out. */
|
||||
export function idToken(): string | undefined { return account() ? current?.idToken : undefined; }
|
||||
|
||||
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
const random = (n = 32) => b64url(crypto.getRandomValues(new Uint8Array(n)));
|
||||
export async function pkceChallenge(verifier: string): Promise<string> {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Server, Trophy } from 'lucide-react';
|
||||
import type { GameMode } from './types.ts';
|
||||
import { pvp, type LadderEntry } from './online.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.
|
||||
@@ -47,3 +48,22 @@ export function Leaderboards({ mode }: { mode: GameMode }) {
|
||||
<p className="muted small">Run a WikiDeck node and host your own modes to appear here.</p></>}
|
||||
</details>;
|
||||
}
|
||||
|
||||
/** Night 2 ladder: Elo per mode keyed to the eom.dev account (host-pvp), W/L when Elo is cut. */
|
||||
export function DuelLadder({ modeId, modeName }: { modeId: string; modeName: string }) {
|
||||
const [entries, setEntries] = useState<LadderEntry[]>();
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
pvp.ladder(modeId).then(e => { if (active) setEntries(e); }, () => { if (active) setEntries([]); });
|
||||
return () => { active = false; };
|
||||
}, [modeId]);
|
||||
const rated = entries?.some(e => e.rating !== null);
|
||||
return <section className="duel-ladder" aria-labelledby="ladder-title">
|
||||
<h3 id="ladder-title" className="lobby-label"><Trophy size={14} /> {modeName} ladder</h3>
|
||||
{entries === undefined ? <p className="muted small">Loading…</p>
|
||||
: entries.length ? <ol className="ladder-list">{entries.map((e, i) => <li key={i}>
|
||||
<small>{i + 1}</small><span>{e.name}</span>{rated ? <b>{e.rating ?? '–'}</b> : <b>{e.wins}W</b>}<small>{e.wins}–{e.losses}{e.draws ? `–${e.draws}` : ''}</small>
|
||||
</li>)}</ol>
|
||||
: <p className="muted small">No ranked matches yet.</p>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
+107
-2
@@ -1,11 +1,11 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { ArrowLeft, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
|
||||
import { ArrowLeft, Copy, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
|
||||
import { DEFAULT_RULESET, type Faction, type GameCard, type Stat } from '../../shared/game/index.ts';
|
||||
import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
|
||||
import { toUICard } from './cards.ts';
|
||||
import { GameCard as GameCardFace } from './GameCard.tsx';
|
||||
import { MatchBoard } from './MatchBoard.tsx';
|
||||
import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
|
||||
import { inviteUrl, online, pvp, type DuelSeat, type DuelStatus, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
|
||||
import type { GameMode, ResultView, UIAction } from './types.ts';
|
||||
|
||||
const POLL_MS = 1000;
|
||||
@@ -126,3 +126,108 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
|
||||
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}><ArrowLeft size={16} /> {phase === 'expired' ? 'Back' : 'Cancel'}</button></div></div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
// ----- Night 2: PvP duels (quick match, private lobby + invite link, join by invite) -----
|
||||
export type DuelEntry = { kind: 'quick' } | { kind: 'private' } | { kind: 'invite'; code: string };
|
||||
|
||||
/** A minimal stand-in until ui-duel's board (src/game/duel) is on the branch: lists legal actions as buttons. */
|
||||
function DuelBoardPlaceholder({ legal, onAct, opponent }: { legal: unknown[]; onAct: (a: unknown) => void; opponent: string }) {
|
||||
const label = (a: unknown) => {
|
||||
const o = (a && typeof a === 'object' ? a : {}) as Record<string, unknown>;
|
||||
const parts = [o.type, o.uid, o.blocker, o.attacker].filter(x => typeof x === 'string' || typeof x === 'number');
|
||||
return parts.join(' · ').slice(0, 60) || 'action';
|
||||
};
|
||||
return <div className="duel-placeholder">
|
||||
<p className="muted small">Playing {opponent}. {legal.length ? 'Your move.' : 'Waiting for your opponent…'}</p>
|
||||
<div className="pvp-grid">{legal.slice(0, 40).map((a, i) => <button key={i} className="pvp-tile" onClick={() => onAct(a)}><b>{label(a)}</b></button>)}</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function DuelOnlinePlay({ modeId, modeName, deck, entry, accountToken, onExit, onRecap }: {
|
||||
modeId: string; modeName: string; deck: string[]; entry: DuelEntry; accountToken: string;
|
||||
onExit: () => void; onRecap: (matchId: string) => void;
|
||||
}) {
|
||||
const [seat, setSeat] = useState<DuelSeat>();
|
||||
const [status, setStatus] = useState<DuelStatus>();
|
||||
const [error, setError] = useState('');
|
||||
const [copied, setCopied] = useState('');
|
||||
const inFlight = useRef(false);
|
||||
const started = useRef(false);
|
||||
const version = useRef(0);
|
||||
const done = status?.phase === 'finished' || status?.phase === 'expired';
|
||||
|
||||
useEffect(() => {
|
||||
if (started.current) return; // StrictMode double-invoke: one seat per entry
|
||||
started.current = true;
|
||||
const go = entry.kind === 'quick' ? pvp.quick(modeId, deck, accountToken)
|
||||
: entry.kind === 'private' ? pvp.createPrivate(modeId, deck, accountToken)
|
||||
: pvp.joinInvite(entry.code, deck, accountToken);
|
||||
go.then(setSeat, e => setError(message(e)));
|
||||
}, [entry, modeId, deck, accountToken]);
|
||||
|
||||
const apply = (s: DuelStatus | null) => { if (s) { version.current = s.version; setStatus(s); } setError(''); };
|
||||
const poll = useCallback(async () => {
|
||||
if (!seat || inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
try { apply(await pvp.status(seat, version.current || undefined)); }
|
||||
catch (e) { setError(message(e)); }
|
||||
finally { inFlight.current = false; }
|
||||
}, [seat]);
|
||||
// Engineer §3: poll fast (500 ms) while waiting on the opponent, slowly (3 s) when it's our move.
|
||||
const myMove = !!status?.legalActions?.length;
|
||||
useEffect(() => {
|
||||
if (!seat || done) return;
|
||||
void poll();
|
||||
const t = setInterval(() => { void poll(); }, myMove ? 3000 : status?.phase === 'waiting' ? 2000 : 500);
|
||||
return () => clearInterval(t);
|
||||
}, [seat, poll, done, myMove, status?.phase]);
|
||||
|
||||
const leave = async () => {
|
||||
if (seat && status && !done) await pvp.resign(seat).catch(() => {});
|
||||
onExit();
|
||||
};
|
||||
/** Resolves once the host accepts the action and rejects on error, so ui-duel's board can send a declaration sequence (#58). */
|
||||
const act = async (a: unknown): Promise<void> => {
|
||||
if (!seat) throw new Error('Not seated.');
|
||||
try { apply(await pvp.act(seat, a)); }
|
||||
catch (e) { setError(message(e)); void poll(); throw e; }
|
||||
};
|
||||
const invite = seat?.invite ?? status?.invite;
|
||||
const link = invite ? inviteUrl(invite) : '';
|
||||
const copy = async () => {
|
||||
try {
|
||||
if (navigator.share) await navigator.share({ title: 'WikiDeck duel', text: `Duel me in WikiDeck (${modeName}).`, url: link });
|
||||
else { await navigator.clipboard.writeText(link); setCopied('Invite link copied.'); }
|
||||
} catch { setCopied('Select the link above and copy it.'); }
|
||||
};
|
||||
const opp = status?.players.find((_, i) => i !== seat?.seat)?.name ?? 'Opponent';
|
||||
const eyebrow = `${modeName.toUpperCase()} · ${entry.kind === 'quick' ? 'QUICK MATCH' : entry.kind === 'private' ? 'PRIVATE LOBBY' : 'INVITE'}`;
|
||||
|
||||
if (status?.phase === 'playing' || status?.phase === 'finished') {
|
||||
const won = status.outcome && status.outcome.winner !== null && status.outcome.winner === seat?.seat;
|
||||
return <section className="play-panel" aria-labelledby="duel-title">
|
||||
<div className="section-eyebrow">{eyebrow}</div>
|
||||
<h2 id="duel-title">{status.phase === 'finished' ? (status.outcome?.winner === null ? 'Draw' : won ? 'Victory' : 'Defeat') : `vs ${opp}`}</h2>
|
||||
{status.phase === 'playing' && <DuelBoardPlaceholder legal={status.legalActions ?? []} onAct={a => { act(a).catch(() => {}); }} opponent={opp} />}
|
||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
||||
<div className="play-dock"><div className="play-actions">
|
||||
<button className="button outline" onClick={leave}>{status.phase === 'finished' ? <><ArrowLeft size={16} /> Back</> : 'Resign'}</button>
|
||||
{status.phase === 'finished' && status.matchId && <button className="button dark play-cta" onClick={() => onRecap(status.matchId!)}>Read the battle recap</button>}
|
||||
</div></div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
return <section className="play-panel" aria-labelledby="wait-title">
|
||||
<div className="section-eyebrow">{eyebrow}</div>
|
||||
<h2 id="wait-title">{status?.phase === 'expired' ? 'This lobby expired' : !seat ? (error ? 'Could not start' : 'Connecting…') : status?.phase === 'starting' ? 'Starting…' : status?.phase === 'drafting' ? 'Drafting…' : entry.kind === 'quick' ? 'Finding an opponent' : 'Waiting for your opponent'}</h2>
|
||||
{seat && link && status?.phase !== 'expired' && <>
|
||||
<p className="muted">Send this link to the person you want to play. It opens this lobby, and they bring their own {deck.length}-card deck.</p>
|
||||
<div className="invite-box"><code aria-label="Invite link">{link}</code><button className="button outline" onClick={copy}><Copy size={14} /> {'share' in navigator ? 'Share' : 'Copy'}</button></div>
|
||||
{copied && <p className="muted small" role="status">{copied}</p>}
|
||||
</>}
|
||||
{seat && !link && status?.phase !== 'expired' && <p className="muted"><LoaderCircle className="spin" size={14} /> {entry.kind === 'quick' ? 'Matching you with a player near your rating.' : 'Joining the lobby.'}</p>}
|
||||
{status?.phase === 'expired' && <p className="muted">Nobody joined in time. Go back and try again.</p>}
|
||||
{error && <p className="dock-error small" role="alert">{error}</p>}
|
||||
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}><ArrowLeft size={16} /> {status?.phase === 'expired' || !seat ? 'Back' : 'Cancel'}</button></div></div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
+92
-98
@@ -1,128 +1,122 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { CircleHelp, ExternalLink, Globe2, Layers3, Play, Server, Swords, UserRound, Users } from 'lucide-react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Bot as BotIcon, Layers3, Link2, LoaderCircle, Lock, UserRound, Zap } from 'lucide-react';
|
||||
import type { TestnetBlock } from '../../shared/testnet.ts';
|
||||
import { Avatar } from '../auth/LoginButton.tsx';
|
||||
import { BOTS, type Bot } from './bots.ts';
|
||||
import { DEFAULT_STARTER, STARTERS, cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from './cards.ts';
|
||||
import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
|
||||
import { CategoryIcon } from './GameCard.tsx';
|
||||
import { Leaderboards } from './Leaderboards.tsx';
|
||||
import { MatchScreen } from './MatchScreen.tsx';
|
||||
import { lobbyName } from './online.ts';
|
||||
import { OnlinePlay } from './OnlinePlay.tsx';
|
||||
import { Results } from './Results.tsx';
|
||||
import { Tutorial } from './Tutorial.tsx';
|
||||
import type { GameMode, ResultView } from './types.ts';
|
||||
import { idToken, login } from '../auth/session.ts';
|
||||
import { DeckPicker, EligibilityGate } from './collection/CollectionScreen.tsx';
|
||||
import { deckProblem, eligibility, fillDeck } from './collection/collection.ts';
|
||||
import { CLASSIC, parseDuelModes, type DuelMode } from './collection/duelModes.ts';
|
||||
import { useCollection } from './collection/useCollection.ts';
|
||||
import { DuelLadder } from './Leaderboards.tsx';
|
||||
import { inviteCode } from './online.ts';
|
||||
import { DuelOnlinePlay, type DuelEntry } from './OnlinePlay.tsx';
|
||||
import { useAccount } from './useAccount.ts';
|
||||
import { useModes } from './useModes.ts';
|
||||
import './play.css';
|
||||
import './collection/pvp.css';
|
||||
|
||||
type Screen = 'lobby' | 'deck' | 'match' | 'online' | 'results' | 'tutorial';
|
||||
const DECK_KEY = 'wikideck-play-deck-v1';
|
||||
const TUTORIAL_KEY = 'wikideck-play-tutorial-v1';
|
||||
const STARTER_KEY = 'wikideck-play-starter-v1';
|
||||
// Night 2 Play: PvP first (BRIEF decision 3). Every deck is 40 cards the player owns (decisions 1–2):
|
||||
// under that, the screen shows progress and how to mine, and offers no borrowed or loaner decks.
|
||||
type Screen = { kind: 'hub' } | { kind: 'deck' } | { kind: 'online'; entry: DuelEntry };
|
||||
const DECK_KEY = 'wikideck-duel-deck-v1';
|
||||
const store = {
|
||||
get: (k: string) => { try { return localStorage.getItem(k); } catch { return null; } },
|
||||
set: (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* storage unavailable */ } },
|
||||
};
|
||||
const playsHere = (m: GameMode) => m.host.kind === 'local' || m.host.self;
|
||||
|
||||
export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
|
||||
const { modes, status } = useModes();
|
||||
export function PlaySection({ owned, onMine, invite: initialInvite = '', onRecap }: {
|
||||
owned: TestnetBlock[]; onMine: () => void; invite?: string; onRecap: (matchId: string) => void;
|
||||
}) {
|
||||
const account = useAccount();
|
||||
const [screen, setScreen] = useState<Screen>(() => store.get(TUTORIAL_KEY) ? 'lobby' : 'tutorial');
|
||||
const [modeId, setModeId] = useState('standard');
|
||||
const [bot, setBot] = useState<Bot>(BOTS[0]);
|
||||
const [savedIds, setSavedIds] = useState<string[] | null>(() => { try { return JSON.parse(store.get(DECK_KEY) ?? 'null'); } catch { return null; } });
|
||||
const [seed, setSeed] = useState('');
|
||||
const [starterId, setStarterId] = useState(() => { const s = store.get(STARTER_KEY); return STARTERS.some(d => d.id === s) ? s! : DEFAULT_STARTER; });
|
||||
const [result, setResult] = useState<ResultView>();
|
||||
const mode = modes.find(m => m.id === modeId) ?? modes[0];
|
||||
const rules = mode.ruleset;
|
||||
const pool = useMemo(() => [...loanerPool(rules), ...owned.map(b => cardFromBlock(b, rules))], [owned, rules]);
|
||||
const { collection: base, status } = useCollection(owned);
|
||||
const [modes, setModes] = useState<DuelMode[]>([CLASSIC]);
|
||||
const [modeId, setModeId] = useState(CLASSIC.id);
|
||||
const [screen, setScreen] = useState<Screen>({ kind: 'hub' });
|
||||
const [pendingInvite, setPendingInvite] = useState(initialInvite);
|
||||
const [joinText, setJoinText] = useState('');
|
||||
const [saved, setSaved] = useState<string[]>(() => { try { const v = JSON.parse(store.get(DECK_KEY) ?? '[]'); return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []; } catch { return []; } });
|
||||
|
||||
// Rebuild the saved deck from current cards; NFTs you no longer own simply drop out.
|
||||
const deck = useMemo(() => {
|
||||
if (!savedIds) return starterDeck(rules, starterId);
|
||||
const byId = new Map(pool.map(c => [c.id, c]));
|
||||
return savedIds.flatMap(id => byId.get(id) ?? []);
|
||||
}, [savedIds, pool, rules, starterId]);
|
||||
const problem = deckProblem(deck, rules);
|
||||
const warning = deckWarning(deck);
|
||||
const opponent = useMemo(() => botDeck(seed, rules), [seed, rules]);
|
||||
|
||||
const [lastOnline, setLastOnline] = useState(false);
|
||||
const start = () => { setLastOnline(false); setSeed(`${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`); setScreen('match'); };
|
||||
const finish = useCallback((r: ResultView) => { setResult(r); setScreen('results'); }, []);
|
||||
useEffect(() => { window.scrollTo?.({ top: 0 }); }, [screen]);
|
||||
// While a match is on screen, hide the floating eom.dev account button (it sits over the dock on phones).
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle('wd-in-match', screen === 'match' || screen === 'online');
|
||||
let active = true;
|
||||
fetch('/api/game/modes', { 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'))))
|
||||
.then(d => { const m = parseDuelModes(d); if (active && m.length) { setModes(m); setModeId(id => (m.some(x => x.id === id) ? id : m[0].id)); } }, () => {});
|
||||
return () => { active = false; };
|
||||
}, []);
|
||||
const mode = modes.find(m => m.id === modeId) ?? modes[0];
|
||||
// A mode may set its own deckSize (testnet end-to-end mode only); production stays at 40.
|
||||
const collection = useMemo(() => (mode.deckSize ? { ...base, deckSize: mode.deckSize } : base), [base, mode.deckSize]);
|
||||
const elig = eligibility(collection);
|
||||
const deck = useMemo(() => fillDeck(saved, collection), [saved, collection]);
|
||||
const problem = deckProblem(deck, collection);
|
||||
const token = idToken();
|
||||
|
||||
useEffect(() => { window.scrollTo?.({ top: 0 }); }, [screen.kind]);
|
||||
useEffect(() => {
|
||||
document.documentElement.classList.toggle('wd-in-match', screen.kind === 'online');
|
||||
document.documentElement.classList.add('wd-play');
|
||||
return () => document.documentElement.classList.remove('wd-in-match', 'wd-play');
|
||||
}, [screen]);
|
||||
}, [screen.kind]);
|
||||
|
||||
if (screen === 'tutorial') return <Tutorial onDone={() => { store.set(TUTORIAL_KEY, '1'); setScreen('lobby'); }} />;
|
||||
if (screen === 'deck') return <DeckBuilder modeName={mode.name} pool={pool} deck={deck} ruleset={rules} onCancel={() => setScreen('lobby')}
|
||||
onSave={d => { const ids = d.map(c => c.id); store.set(DECK_KEY, JSON.stringify(ids)); setSavedIds(ids); setScreen('lobby'); }} />;
|
||||
if (screen === 'match') return <MatchScreen key={seed} mode={mode} deck={deck} opponentDeck={opponent} bot={bot} seed={seed} onFinish={finish} />;
|
||||
if (screen === 'online') return <OnlinePlay key={mode.id} mode={mode} playerName={lobbyName(account?.name || account?.username)} onExit={() => setScreen('lobby')} onFinish={finish} />;
|
||||
if (screen === 'results' && result) return <Results result={result} modeName={mode.name} onRematch={lastOnline ? () => setScreen('online') : start} onLobby={() => setScreen('lobby')} />;
|
||||
const playOnline = (entry: DuelEntry) => { setPendingInvite(''); setScreen({ kind: 'online', entry }); };
|
||||
if (screen.kind === 'deck') return <DeckPicker collection={collection} deck={deck} onCancel={() => setScreen({ kind: 'hub' })}
|
||||
onSave={d => { store.set(DECK_KEY, JSON.stringify(d)); setSaved(d); setScreen({ kind: 'hub' }); }} />;
|
||||
if (screen.kind === 'online' && token) return <DuelOnlinePlay key={JSON.stringify(screen.entry)} modeId={mode.id} modeName={mode.name} deck={deck}
|
||||
entry={screen.entry} accountToken={token} onExit={() => setScreen({ kind: 'hub' })} onRecap={onRecap} />;
|
||||
|
||||
const remote = mode.host.kind === 'peer' && !mode.host.self ? mode.host : null;
|
||||
const hosted = mode.host.kind === 'peer' && mode.host.self;
|
||||
const ready = elig.eligible && !problem && !!token;
|
||||
const why = !token ? 'Log in with your eom.dev account to play people.' : !elig.eligible ? '' : problem;
|
||||
const joinCode = inviteCode(joinText);
|
||||
return <section className="play-panel lobby" aria-labelledby="lobby-title">
|
||||
<div className="lobby-head">
|
||||
<div><div className="section-eyebrow">PLAY · OFF-CHAIN MATCHES</div><h2 id="lobby-title">Play WikiDeck</h2></div>
|
||||
<div><div className="section-eyebrow">PLAY · OFF-CHAIN DUELS</div><h2 id="lobby-title">Play WikiDeck</h2></div>
|
||||
<div className="account-chip" aria-label="eom.dev account">{account
|
||||
? <><Avatar name={account.name || account.username} seed={account.sub} /><span>{account.name || account.username}</span></>
|
||||
: <><UserRound size={15} /><span>Guest</span></>}
|
||||
</div>
|
||||
</div>
|
||||
<p className="muted">Three Topics, six turns: win two Topics. Each Topic is judged on one Wikipedia stat, and cards are stronger on their home stat. New here? You already have a loaner starter deck. Matches never move or burn your cards.</p>
|
||||
<p className="muted">A duel between two {collection.deckSize}-card decks built from cards you own. Matches never move or burn your cards.</p>
|
||||
|
||||
<h3 className="lobby-label">Mode</h3>
|
||||
<div className="mode-list" role="radiogroup" aria-label="Game mode">
|
||||
{modes.map(m => <button key={m.id} role="radio" aria-checked={m.id === mode.id} className={`mode ${m.id === mode.id ? 'selected' : ''}`} onClick={() => setModeId(m.id)}>
|
||||
<span className="mode-icon">{m.host.kind === 'local' ? <Swords size={18} /> : <Server size={18} />}</span>
|
||||
<span className="mode-copy"><b>{m.name}</b>{m.description && <small>{m.description}</small>}
|
||||
<small className="mode-host">{m.host.kind === 'local' ? 'Built in · plays in your browser' : `Hosted by ${m.host.name}`}
|
||||
{m.players !== undefined ? ` · ${m.players} online` : ''}{m.matchesPlayed !== undefined ? ` · ${m.matchesPlayed} played` : ''}</small></span>
|
||||
</button>)}
|
||||
{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>}
|
||||
</div>
|
||||
{status === 'ok' && <Leaderboards key={mode.id} mode={mode} />}
|
||||
{pendingInvite && <div className="eligibility" role="status">
|
||||
<b>You have been invited to a duel.</b>
|
||||
<p className="muted small">{ready ? 'Your saved deck is ready.' : why || `You need ${collection.deckSize} cards of your own to accept.`}</p>
|
||||
<div className="eligibility-actions">
|
||||
<button className="button dark" disabled={!ready} onClick={() => playOnline({ kind: 'invite', code: pendingInvite })}><Link2 size={16} /> Accept invite</button>
|
||||
<button className="button outline" onClick={() => setPendingInvite('')}>Dismiss</button>
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{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>
|
||||
<div className="play-dock"><div className="play-actions">
|
||||
<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>
|
||||
: <button className="button dark play-cta" disabled>Host address unavailable</button>}
|
||||
</div></div>
|
||||
</> : <>
|
||||
<h3 className="lobby-label">Opponent</h3>
|
||||
<div className="category-tabs">{BOTS.map(b => <button key={b.id} className={bot.id === b.id ? 'selected' : ''} onClick={() => setBot(b)}>{b.name} bot</button>)}</div>
|
||||
{modes.length > 1 && <><h3 className="lobby-label">Mode</h3>
|
||||
<div className="category-tabs" role="radiogroup" aria-label="Game mode">{modes.map(m =>
|
||||
<button key={m.id} role="radio" aria-checked={m.id === mode.id} className={m.id === mode.id ? 'selected' : ''} onClick={() => setModeId(m.id)}>{m.name}</button>)}</div></>}
|
||||
|
||||
<h3 className="lobby-label">Deck <span className="count-badge">{deck.length}</span></h3>
|
||||
<button className="deck-summary" onClick={() => setScreen('deck')} aria-label="Edit deck">
|
||||
<span className="deck-fan" aria-hidden="true">{deck.slice(0, 4).map(c => <span key={c.id} className={`fan-chip cat-${c.category.toLowerCase()}`}><CategoryIcon category={c.category} size={14} /></span>)}</span>
|
||||
<span><b>{savedIds ? 'Your deck' : `Starter: ${STARTERS.find(d => d.id === starterId)?.name}`}</b><small>{deck.filter(c => c.source === 'nft').length} NFTs · {deck.filter(c => c.source === 'starter').length} loaners</small></span>
|
||||
<Layers3 size={18} />
|
||||
</button>
|
||||
{!savedIds && <div className="category-tabs starter-picks" role="radiogroup" aria-label="Starter deck">{STARTERS.map(d =>
|
||||
<button key={d.id} role="radio" aria-checked={starterId === d.id} className={starterId === d.id ? 'selected' : ''}
|
||||
onClick={() => { setStarterId(d.id); store.set(STARTER_KEY, d.id); }}>{d.name}</button>)}</div>}
|
||||
{savedIds && <button className="text-button" onClick={() => { setSavedIds(null); try { localStorage.removeItem(DECK_KEY); } catch { /* ignore */ } }}>Use a starter deck instead</button>}
|
||||
{problem ? <p className="dock-error small">{problem} Edit your deck to play {mode.name}.</p>
|
||||
: warning && <p className="deck-warning small">{warning}</p>}
|
||||
{status === 'loading' ? <p className="muted"><LoaderCircle className="spin" size={14} /> Counting your cards…</p>
|
||||
: !elig.eligible ? <EligibilityGate collection={collection} onMine={onMine} guest={!account} onLogin={() => void login()} />
|
||||
: <>
|
||||
<h3 className="lobby-label">Deck <span className={`count-badge ${problem ? '' : 'ok'}`}>{deck.length} / {collection.deckSize}</span></h3>
|
||||
<button className="deck-summary" onClick={() => setScreen({ kind: 'deck' })} aria-label="Edit deck">
|
||||
<span><b>{saved.length ? 'Your deck' : 'Auto-built from your collection'}</b><small>{collection.cards.length} cards owned · {elig.playable} playable</small></span>
|
||||
<Layers3 size={18} />
|
||||
</button>
|
||||
{status === 'fallback' && <p className="muted small">Showing this browser’s wallet. The host checks every card you own before a match.</p>}
|
||||
{why && <p className="dock-error small">{why}</p>}
|
||||
{!token && <button className="button outline" onClick={() => void login()}>Log in with eom.dev</button>}
|
||||
|
||||
<div className="play-dock"><div className="play-actions">
|
||||
<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" 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" 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>
|
||||
</>}
|
||||
<h3 className="lobby-label">Play a person</h3>
|
||||
<div className="pvp-grid">
|
||||
<button className="pvp-tile primary" disabled={!ready} onClick={() => playOnline({ kind: 'quick' })}><Zap size={20} />
|
||||
<span><b>Quick match</b><small>{mode.ranked ? 'Ranked · paired near your rating' : 'Paired with the next player waiting'}</small></span></button>
|
||||
<button className="pvp-tile" disabled={!ready} onClick={() => playOnline({ kind: 'private' })}><Lock size={20} />
|
||||
<span><b>Private lobby</b><small>Get an invite link to send a friend</small></span></button>
|
||||
</div>
|
||||
<form className="pvp-join" onSubmit={e => { e.preventDefault(); if (joinCode && ready) playOnline({ kind: 'invite', code: joinCode }); }}>
|
||||
<input value={joinText} onChange={e => setJoinText(e.target.value)} placeholder="Paste an invite link" aria-label="Invite link or code" />
|
||||
<button className="button outline" type="submit" disabled={!ready || !joinCode}><Link2 size={14} /> Join</button>
|
||||
</form>
|
||||
|
||||
<h3 className="lobby-label">Practice</h3>
|
||||
<button className="pvp-tile" disabled><BotIcon size={20} /><span><b>Bot match</b><small>Opens with the duel board</small></span></button>
|
||||
</>}
|
||||
|
||||
<DuelLadder key={mode.id} modeId={mode.id} modeName={mode.name} />
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useState } from 'react';
|
||||
import { Check, ExternalLink, Pickaxe, RotateCcw, Search } from 'lucide-react';
|
||||
import { deckProblem, eligibility, fillDeck, progressLabel, type Collection, type CollectionCard } from './collection.ts';
|
||||
|
||||
/** Under deckSize playable cards: progress and how to mine. No borrowed decks (BRIEF decision 2). */
|
||||
export function EligibilityGate({ collection, onMine, guest, onLogin }: {
|
||||
collection: Collection; onMine: () => void; guest: boolean; onLogin?: () => void;
|
||||
}) {
|
||||
const e = eligibility(collection);
|
||||
const pct = Math.round((Math.min(e.playable, e.deckSize) / e.deckSize) * 100);
|
||||
const dupes = e.owned - e.playable;
|
||||
return <div className="eligibility" aria-labelledby="eligibility-title">
|
||||
<h3 id="eligibility-title" className="eligibility-count">{progressLabel(e)}. Mine to play</h3>
|
||||
<div className="eligibility-bar" role="progressbar" aria-valuemin={0} aria-valuemax={e.deckSize} aria-valuenow={Math.min(e.playable, e.deckSize)}
|
||||
aria-label={`${progressLabel(e)} owned`}><span style={{ width: `${pct}%` }} /></div>
|
||||
<p className="muted">A WikiDeck deck is exactly {e.deckSize} cards, and every one is a card you mined or traded for. You need {e.needed} more{dupes > 0 ? ` (${dupes} of your cards are extra copies over the ${collection.copyLimit}-per-article limit)` : ''}. Each accepted block mints one card.</p>
|
||||
{guest && <p className="muted small">Log in with your eom.dev account to count cards in every wallet you have linked.</p>}
|
||||
<div className="eligibility-actions">
|
||||
<button className="button dark" onClick={onMine}><Pickaxe size={16} /> Mine cards</button>
|
||||
{guest && onLogin && <button className="button outline" onClick={onLogin}>Log in</button>}
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
const byTitle = (a: CollectionCard, b: CollectionCard) => a.title.localeCompare(b.title) || a.tokenId.localeCompare(b.tokenId);
|
||||
|
||||
/** Constructed deck from owned cards only: exactly deckSize, at most copyLimit per article. */
|
||||
export function DeckPicker({ collection, deck, onSave, onCancel }: {
|
||||
collection: Collection; deck: string[]; onSave: (deck: string[]) => void; onCancel: () => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<string[]>(() => deck.filter(id => collection.cards.some(c => c.tokenId === id)));
|
||||
const [query, setQuery] = useState('');
|
||||
const inDeck = new Set(draft);
|
||||
const perPage = new Map<number, number>();
|
||||
for (const c of collection.cards) if (inDeck.has(c.tokenId)) perPage.set(c.pageId, (perPage.get(c.pageId) ?? 0) + 1);
|
||||
const shown = collection.cards.filter(c => c.title.toLowerCase().includes(query.trim().toLowerCase())).sort(byTitle);
|
||||
const problem = deckProblem(draft, collection);
|
||||
const full = draft.length >= collection.deckSize;
|
||||
const toggle = (c: CollectionCard) => setDraft(d => d.includes(c.tokenId) ? d.filter(x => x !== c.tokenId)
|
||||
: d.length >= collection.deckSize || (perPage.get(c.pageId) ?? 0) >= collection.copyLimit ? d : [...d, c.tokenId]);
|
||||
|
||||
return <section className="play-panel deck-picker" aria-labelledby="picker-title">
|
||||
<div className="section-eyebrow">CONSTRUCTED · YOUR CARDS ONLY</div>
|
||||
<h2 id="picker-title">Your deck <span className={`count-badge ${problem ? '' : 'ok'}`}>{draft.length} / {collection.deckSize}</span></h2>
|
||||
<p className="muted small">Pick exactly {collection.deckSize} of your {collection.cards.length} cards. At most {collection.copyLimit} copies of one article.</p>
|
||||
<div className="picker-tools">
|
||||
<label className="picker-search"><Search size={14} /><input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search your cards" aria-label="Search your cards" /></label>
|
||||
<button className="button outline" onClick={() => setDraft(fillDeck(draft, collection))} disabled={full}>Fill</button>
|
||||
<button className="button outline" aria-label="Clear deck" onClick={() => setDraft([])}><RotateCcw size={14} /></button>
|
||||
</div>
|
||||
<ul className="picker-list">{shown.map(c => {
|
||||
const on = inDeck.has(c.tokenId);
|
||||
const blocked = !on && (full || (perPage.get(c.pageId) ?? 0) >= collection.copyLimit);
|
||||
return <li key={c.tokenId}>
|
||||
<button className={`picker-row ${on ? 'selected' : ''}`} aria-pressed={on} disabled={blocked} onClick={() => toggle(c)}>
|
||||
<span className="picker-check" aria-hidden="true">{on && <Check size={14} />}</span>
|
||||
<span className="picker-title">{c.title}</span>
|
||||
<small>{c.category ?? ''}{c.height !== undefined ? ` · #${c.height}` : ''}</small>
|
||||
</button>
|
||||
{c.url && <a className="picker-link" href={c.url} target="_blank" rel="noopener noreferrer" aria-label={`${c.title} on Wikipedia`}><ExternalLink size={13} /></a>}
|
||||
</li>;
|
||||
})}</ul>
|
||||
{problem && <p className="dock-error small" role="status">{problem}</p>}
|
||||
<div className="play-dock"><div className="play-actions">
|
||||
<button className="button outline" onClick={onCancel}>Cancel</button>
|
||||
<button className="button dark play-cta" disabled={!!problem} onClick={() => onSave(draft)}><Check size={16} /> Save deck</button>
|
||||
</div></div>
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Collection and 40-card eligibility (Night 2, BRIEF decisions 1–2). Every deck card is an NFT the
|
||||
// player owns: no loaners, Basics or proxies. The server (ownership's GET /api/game/collection) is the
|
||||
// authority; the browser copy is only a fallback view while that endpoint is unavailable, and the
|
||||
// host re-verifies every deck on the server anyway. Every response is untrusted input.
|
||||
import type { TestnetBlock } from '../../../shared/testnet.ts';
|
||||
|
||||
export const DEFAULT_DECK_SIZE = 40;
|
||||
export const DEFAULT_COPY_LIMIT = 4;
|
||||
|
||||
export type CollectionCard = {
|
||||
tokenId: string; pageId: number; title: string; revisionId?: number;
|
||||
url?: string; imageUrl?: string; extract?: string; category?: string; height?: number;
|
||||
/** Server-derived, frozen duel profile (ownership adds it for ui-duel's bot match, #58). Passed through untouched. */
|
||||
duel?: unknown;
|
||||
};
|
||||
export type Collection = {
|
||||
deckSize: number; copyLimit: number; cards: CollectionCard[];
|
||||
/** 'server' = ownership API (authoritative); 'local' = this browser's wallet view (fallback). */
|
||||
source: 'server' | 'local';
|
||||
};
|
||||
|
||||
const str = (v: unknown, max = 300) => (typeof v === 'string' ? v.slice(0, max) : '');
|
||||
const int = (v: unknown, min = 0, max = Number.MAX_SAFE_INTEGER) =>
|
||||
(typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max ? v : undefined);
|
||||
const httpUrl = (v: unknown) => { const s = str(v, 2000); return /^https:\/\//i.test(s) ? s : undefined; };
|
||||
|
||||
/** Parse ownership's collection response. Unknown fields are ignored, bad cards dropped, duplicates by tokenId removed. */
|
||||
export function parseCollection(v: unknown): Collection {
|
||||
const o = v && typeof v === 'object' ? v as Record<string, unknown> : {};
|
||||
const list = Array.isArray(o.cards) ? o.cards : [];
|
||||
const seen = new Set<string>();
|
||||
const cards: CollectionCard[] = [];
|
||||
for (const raw of list.slice(0, 5000)) {
|
||||
if (!raw || typeof raw !== 'object') continue;
|
||||
const c = raw as Record<string, unknown>;
|
||||
const tokenId = str(c.tokenId, 128);
|
||||
const pageId = int(c.pageId, 1);
|
||||
if (!tokenId || pageId === undefined || seen.has(tokenId)) continue;
|
||||
seen.add(tokenId);
|
||||
cards.push({ tokenId, pageId, title: str(c.title, 200) || `Page ${pageId}`, revisionId: int(c.revisionId, 1),
|
||||
url: httpUrl(c.url), imageUrl: httpUrl(c.imageUrl ?? c.image), extract: str(c.extract, 600) || undefined,
|
||||
category: str(c.category, 40) || undefined, height: int(c.height), ...(c.duel && typeof c.duel === 'object' ? { duel: c.duel } : {}) });
|
||||
}
|
||||
return { deckSize: int(o.deckSize, 1, 200) ?? DEFAULT_DECK_SIZE, copyLimit: int(o.copyLimit, 1, 200) ?? DEFAULT_COPY_LIMIT, cards, source: 'server' };
|
||||
}
|
||||
|
||||
/** Fallback while the ownership API isn't reachable: the confirmed blocks this browser's wallet owns. */
|
||||
export function collectionFromBlocks(blocks: TestnetBlock[], deckSize = DEFAULT_DECK_SIZE, copyLimit = DEFAULT_COPY_LIMIT): Collection {
|
||||
return { deckSize, copyLimit, source: 'local', cards: blocks.map(b => ({
|
||||
tokenId: b.tokenId, pageId: b.article.pageId, title: b.article.title, revisionId: b.article.revisionId,
|
||||
url: b.article.url, imageUrl: b.article.image, extract: b.article.extract, category: b.article.category, height: b.height,
|
||||
})) };
|
||||
}
|
||||
|
||||
/** Cards that can go into one deck: at most `copyLimit` per article (pageId). */
|
||||
export function playableCount(c: Pick<Collection, 'cards' | 'copyLimit'>): number {
|
||||
const per = new Map<number, number>();
|
||||
for (const card of c.cards) per.set(card.pageId, (per.get(card.pageId) ?? 0) + 1);
|
||||
let n = 0;
|
||||
for (const k of per.values()) n += Math.min(k, c.copyLimit);
|
||||
return n;
|
||||
}
|
||||
|
||||
export type Eligibility = { eligible: boolean; owned: number; playable: number; needed: number; deckSize: number };
|
||||
export function eligibility(c: Collection): Eligibility {
|
||||
const playable = playableCount(c);
|
||||
return { eligible: playable >= c.deckSize, owned: c.cards.length, playable, needed: Math.max(0, c.deckSize - playable), deckSize: c.deckSize };
|
||||
}
|
||||
|
||||
/** "23 / 40 cards" progress copy. */
|
||||
export const progressLabel = (e: Eligibility) => `${Math.min(e.playable, e.deckSize)} / ${e.deckSize} cards`;
|
||||
|
||||
/** Why a deck (a list of tokenIds) can't be played, or '' when it is a legal constructed deck. */
|
||||
export function deckProblem(deck: string[], c: Collection): string {
|
||||
if (deck.length !== c.deckSize) return `A deck needs exactly ${c.deckSize} cards (${deck.length} now).`;
|
||||
const byId = new Map(c.cards.map(card => [card.tokenId, card]));
|
||||
const seen = new Set<string>();
|
||||
const per = new Map<number, number>();
|
||||
for (const id of deck) {
|
||||
const card = byId.get(id);
|
||||
if (!card) return 'Your deck includes a card you no longer own. Remove it and pick another.';
|
||||
if (seen.has(id)) return 'The same card is in your deck twice.';
|
||||
seen.add(id);
|
||||
const n = (per.get(card.pageId) ?? 0) + 1;
|
||||
per.set(card.pageId, n);
|
||||
if (n > c.copyLimit) return `At most ${c.copyLimit} copies of “${card.title}” fit in one deck.`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the saved deck's cards that are still owned and fill to deckSize from the rest of the
|
||||
* collection, respecting the copy limit. Deterministic (collection order), so the result is stable.
|
||||
*/
|
||||
export function fillDeck(saved: string[], c: Collection): string[] {
|
||||
const byId = new Map(c.cards.map(card => [card.tokenId, card]));
|
||||
const per = new Map<number, number>();
|
||||
const out: string[] = [];
|
||||
const add = (card: CollectionCard) => {
|
||||
if (out.length >= c.deckSize || out.includes(card.tokenId)) return;
|
||||
const n = per.get(card.pageId) ?? 0;
|
||||
if (n >= c.copyLimit) return;
|
||||
per.set(card.pageId, n + 1); out.push(card.tokenId);
|
||||
};
|
||||
for (const id of saved) { const card = byId.get(id); if (card) add(card); }
|
||||
for (const card of c.cards) add(card);
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Duel modes hosted by this node (host-pvp adds `engine: 'duel'` to modes, #56). Until that lands,
|
||||
// or when the list is unreachable, Classic (constructed, ranked) is assumed. Untrusted input.
|
||||
export type DuelMode = { id: string; name: string; description: string; ranked: boolean; deckSize?: number };
|
||||
export const CLASSIC: DuelMode = { id: 'classic', name: 'Classic', description: 'Constructed from your own 40 cards. Ranked.', ranked: true };
|
||||
|
||||
const str = (v: unknown, max: number) => (typeof v === 'string' ? v.slice(0, max) : '');
|
||||
const obj = (v: unknown) => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : undefined);
|
||||
|
||||
export function parseDuelModes(data: unknown): DuelMode[] {
|
||||
const list = obj(data)?.modes;
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list.slice(0, 16).flatMap((entry): DuelMode[] => {
|
||||
const m = obj(obj(entry)?.mode) ?? obj(entry);
|
||||
if (!m || m.engine !== 'duel') return [];
|
||||
const id = str(m.id, 64), name = str(m.name, 60);
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(id) || !name) return [];
|
||||
const rules = obj(m.rules), limits = obj(m.limits);
|
||||
const deckSize = typeof rules?.deckSize === 'number' && Number.isInteger(rules.deckSize) && rules.deckSize > 0 ? rules.deckSize : undefined;
|
||||
return [{ id, name, description: str(m.description, 280), ranked: limits?.rated === true || m.rated === true, ...(deckSize ? { deckSize } : {}) }];
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/* PvP hub, eligibility gate and constructed deck picker (ui-pvp). 360 px first. */
|
||||
.eligibility{border:1px solid var(--theme-border);border-radius:12px;padding:14px;background:var(--ctp-base);margin:12px 0}
|
||||
.eligibility-count{font-size:20px;margin:0 0 8px}
|
||||
.eligibility-bar{height:10px;border-radius:5px;background:var(--ctp-surface0);overflow:hidden;margin-bottom:10px}
|
||||
.eligibility-bar span{display:block;height:100%;background:var(--ctp-green);border-radius:5px}
|
||||
.eligibility-actions{display:flex;gap:8px;flex-wrap:wrap}
|
||||
.eligibility-actions .button{min-height:44px}
|
||||
.pvp-grid{display:grid;grid-template-columns:1fr;gap:8px;margin:10px 0}
|
||||
.pvp-tile{display:flex;align-items:center;gap:12px;text-align:left;min-height:56px;padding:10px 12px;border:1px solid var(--theme-border);border-radius:10px;background:var(--ctp-base);color:var(--ctp-text);cursor:pointer;font:inherit;width:100%}
|
||||
.pvp-tile:disabled{opacity:.55;cursor:not-allowed}
|
||||
.pvp-tile b{display:block;font-size:14px}
|
||||
.pvp-tile small{display:block;font-size:11px;color:var(--ctp-subtext0)}
|
||||
.pvp-tile.primary{border-color:var(--ctp-mauve);background:var(--ctp-surface0)}
|
||||
.pvp-join{display:flex;gap:6px}
|
||||
.pvp-join input,.picker-search input{flex:1;min-width:0;min-height:44px;padding:8px 10px;border-radius:8px;border:1px solid var(--theme-border);background:var(--ctp-base);color:var(--ctp-text);font:inherit;font-size:14px}
|
||||
.invite-box{display:flex;gap:6px;align-items:stretch;margin:8px 0}
|
||||
.invite-box code{flex:1;min-width:0;overflow-wrap:anywhere;padding:10px;border-radius:8px;background:var(--ctp-base);border:1px solid var(--theme-border);font-size:12px}
|
||||
.ladder-list{list-style:none;padding:0;margin:6px 0;font-size:13px}
|
||||
.ladder-list li{display:grid;grid-template-columns:24px 1fr auto auto;gap:8px;padding:6px 4px;border-bottom:1px solid var(--theme-border)}
|
||||
.ladder-list li b{font-variant-numeric:tabular-nums}
|
||||
.ladder-list li small{color:var(--ctp-subtext0);font-variant-numeric:tabular-nums}
|
||||
.picker-tools{display:flex;gap:6px;margin:8px 0}
|
||||
.picker-tools .button{min-height:44px;padding:8px 12px}
|
||||
.picker-search{flex:1;display:flex;align-items:center;gap:6px;min-width:0}
|
||||
.picker-list{list-style:none;padding:0;margin:0 0 8px;max-height:55vh;overflow:auto}
|
||||
.picker-list li{display:flex;align-items:center;gap:4px;border-bottom:1px solid var(--theme-border)}
|
||||
.picker-row{flex:1;display:grid;grid-template-columns:22px 1fr auto;align-items:center;gap:8px;min-height:44px;padding:6px 4px;background:none;border:0;color:var(--ctp-text);font:inherit;text-align:left;cursor:pointer;min-width:0}
|
||||
.picker-row:disabled{opacity:.45;cursor:not-allowed}
|
||||
.picker-row.selected .picker-check{background:var(--ctp-green);color:var(--ctp-base);border-color:var(--ctp-green)}
|
||||
.picker-check{width:20px;height:20px;border-radius:5px;border:1px solid var(--theme-border);display:grid;place-items:center}
|
||||
.picker-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px}
|
||||
.picker-row small{font-size:11px;color:var(--ctp-subtext0)}
|
||||
.picker-link{padding:10px;color:var(--ctp-subtext0)}
|
||||
.duel-placeholder{border:1px dashed var(--theme-border);border-radius:10px;padding:14px;margin:10px 0;font-size:13px}
|
||||
@media (min-width:640px){.pvp-grid{grid-template-columns:1fr 1fr}}
|
||||
.lobby .deck-summary b,.lobby .deck-summary small{display:block}
|
||||
.eligibility-bar+p{margin-bottom:12px}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { TestnetBlock } from '../../../shared/testnet.ts';
|
||||
import { idToken } from '../../auth/session.ts';
|
||||
import { useAccount } from '../useAccount.ts';
|
||||
import { collectionFromBlocks, parseCollection, type Collection } from './collection.ts';
|
||||
|
||||
export type CollectionState = { collection: Collection; status: 'loading' | 'ok' | 'fallback' | 'guest' };
|
||||
|
||||
/**
|
||||
* The player's owned cards. Logged in: ownership's GET /api/game/collection (all linked wallets,
|
||||
* no snapshot cap). Logged out or API unavailable: this browser wallet's confirmed cards, shown
|
||||
* as a view only (the host still verifies on the server before any match).
|
||||
*/
|
||||
export function useCollection(owned: TestnetBlock[]): CollectionState {
|
||||
const account = useAccount();
|
||||
const local = useMemo(() => collectionFromBlocks(owned), [owned]);
|
||||
const [server, setServer] = useState<{ sub: string; c?: Collection; failed?: boolean }>();
|
||||
const sub = account?.sub ?? '';
|
||||
useEffect(() => {
|
||||
const token = idToken();
|
||||
if (!sub || !token) { setServer(undefined); return; }
|
||||
let active = true;
|
||||
setServer({ sub });
|
||||
fetch('/api/game/collection', { cache: 'no-store', headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15000) })
|
||||
.then(r => (r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error(String(r.status)))))
|
||||
.then(d => { if (active) setServer({ sub, c: parseCollection(d) }); }, () => { if (active) setServer({ sub, failed: true }); });
|
||||
return () => { active = false; };
|
||||
}, [sub]);
|
||||
if (!sub) return { collection: local, status: 'guest' };
|
||||
if (server?.sub === sub && server.c) return { collection: server.c, status: 'ok' };
|
||||
if (server?.sub === sub && server.failed) return { collection: local, status: 'fallback' };
|
||||
return { collection: local, status: 'loading' };
|
||||
}
|
||||
@@ -74,3 +74,109 @@ export const online = {
|
||||
pick: (s: LobbySeat, index: number) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/pick`, { body: { index }, token: s.token }),
|
||||
resign: (s: LobbySeat) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }),
|
||||
};
|
||||
|
||||
// ----- Night 2: PvP duel client (host-pvp, #56). Seats are bound to the eom.dev account: every call
|
||||
// joins with the Dex ID token, then uses the seat token. Routes are stubbed against the shapes
|
||||
// posted on #56 until docs/game/DUEL_API.md lands; parsers below treat every response as untrusted.
|
||||
export type DuelSeat = { lobbyId: string; seat: 0 | 1; token: string; invite?: string };
|
||||
export type DuelStatus = {
|
||||
lobbyId: string; version: number;
|
||||
phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
|
||||
seat: 0 | 1 | null; players: { name: string; rating?: number }[];
|
||||
outcome: { winner: 0 | 1 | null; reason: string } | null;
|
||||
matchId?: string; invite?: string;
|
||||
/** Duel engine PlayerView and legal actions (shared/duel/types.ts), passed through to the board. */
|
||||
state?: unknown; legalActions?: unknown[];
|
||||
};
|
||||
export type LadderEntry = { name: string; rating: number | null; wins: number; losses: number; draws: number };
|
||||
|
||||
const sid = (v: unknown, max = 128) => (typeof v === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(v) ? v.slice(0, max) : '');
|
||||
const seatNo = (v: unknown): 0 | 1 | null => (v === 0 || v === 1 ? v : null);
|
||||
const PHASES = new Set(['waiting', 'starting', 'drafting', 'playing', 'finished', 'expired']);
|
||||
|
||||
export function parseSeat(v: unknown): DuelSeat {
|
||||
const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
|
||||
const lobbyId = sid(o.lobbyId), token = typeof o.token === 'string' ? o.token.slice(0, 512) : '', seat = seatNo(o.seat);
|
||||
if (!lobbyId || !token || seat === null) throw new Error('The host sent an invalid seat.');
|
||||
const invite = sid(o.invite ?? o.inviteCode);
|
||||
return { lobbyId, seat, token, ...(invite ? { invite } : {}) };
|
||||
}
|
||||
|
||||
export function parseDuelStatus(v: unknown): DuelStatus {
|
||||
const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
|
||||
const phase = PHASES.has(o.phase as string) ? o.phase as DuelStatus['phase'] : 'waiting';
|
||||
const players = (Array.isArray(o.players) ? o.players : []).slice(0, 2).map(p => {
|
||||
const r = (p && typeof p === 'object' ? p : {}) as Record<string, unknown>;
|
||||
return { name: typeof r.name === 'string' ? r.name.slice(0, 24) : 'Player', ...(typeof r.rating === 'number' && Number.isFinite(r.rating) ? { rating: Math.round(r.rating) } : {}) };
|
||||
});
|
||||
const out = o.outcome && typeof o.outcome === 'object' ? o.outcome as Record<string, unknown> : null;
|
||||
const matchId = sid(o.matchId), invite = sid(o.invite ?? o.inviteCode);
|
||||
return {
|
||||
lobbyId: sid(o.lobbyId), version: typeof o.version === 'number' && Number.isFinite(o.version) ? o.version : 0, phase,
|
||||
seat: seatNo(o.seat), players, outcome: out ? { winner: seatNo(out.winner), reason: typeof out.reason === 'string' ? out.reason.slice(0, 80) : '' } : null,
|
||||
...(matchId ? { matchId } : {}), ...(invite ? { invite } : {}),
|
||||
...(o.state !== undefined ? { state: o.state } : {}), ...(Array.isArray(o.legalActions) ? { legalActions: o.legalActions.slice(0, 500) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseLadder(v: unknown): LadderEntry[] {
|
||||
const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
|
||||
const list = Array.isArray(o.entries) ? o.entries : [];
|
||||
const n = (x: unknown) => (typeof x === 'number' && Number.isFinite(x) && x >= 0 ? Math.floor(x) : 0);
|
||||
return list.filter((e): e is Record<string, unknown> => !!e && typeof e === 'object').slice(0, 50).map(e => ({
|
||||
name: typeof e.name === 'string' && e.name.trim() ? e.name.slice(0, 24) : 'Anonymous',
|
||||
rating: typeof e.rating === 'number' && Number.isFinite(e.rating) ? Math.round(e.rating) : null,
|
||||
wins: n(e.wins), losses: n(e.losses), draws: n(e.draws),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Pull an invite code out of a pasted link (…/play/invite/<code>) or a bare code. */
|
||||
export function inviteCode(input: string): string {
|
||||
const s = input.trim();
|
||||
const m = s.match(/\/play\/(?:invite|join)\/([A-Za-z0-9_-]{1,128})\/?(?:[?#].*)?$/);
|
||||
return m ? m[1] : /^[A-Za-z0-9_-]{4,128}$/.test(s) ? s : '';
|
||||
}
|
||||
/** /play/invite/<code> (or the older /play/join/<id>) → the invite code, else ''. */
|
||||
export const inviteFromPath = (path: string) => (/^\/play\/(invite|join)\//.test(path) ? inviteCode(path) : '');
|
||||
export const inviteUrl = (code: string, origin = location.origin) => `${origin}/play/invite/${encodeURIComponent(code)}`;
|
||||
|
||||
type DuelInit = { method?: string; body?: unknown; seat?: string };
|
||||
// host-pvp (#56): create/join carry the Dex ID token in the body ({idToken}); Bearer stays the seat token.
|
||||
async function duelCall(path: string, init: DuelInit = {}): Promise<{ status: number; data: unknown }> {
|
||||
const headers: Record<string, string> = {};
|
||||
if (init.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (init.seat) headers.Authorization = `Bearer ${init.seat}`;
|
||||
const res = await fetch(`/api/game/${path}`, {
|
||||
method: init.method ?? (init.body === undefined ? 'GET' : 'POST'), cache: 'no-store', signal: AbortSignal.timeout(10000), headers,
|
||||
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
|
||||
});
|
||||
if (res.status === 204) return { status: 204, data: null };
|
||||
const data = res.headers.get('content-type')?.includes('json') ? await res.json().catch(() => ({})) : {};
|
||||
if (!res.ok) {
|
||||
const err = (data as { error?: unknown })?.error;
|
||||
throw Object.assign(new Error(typeof err === 'string' ? err.slice(0, 200) : res.status === 401 ? 'Log in with your eom.dev account to play.' : `The host answered ${res.status}.`), { status: res.status });
|
||||
}
|
||||
return { status: res.status, data };
|
||||
}
|
||||
|
||||
export const pvp = {
|
||||
createPrivate: (modeId: string, deck: string[], idToken: string) =>
|
||||
duelCall(`modes/${id(modeId)}/lobbies`, { body: { deck, private: true, idToken } }).then(r => parseSeat(r.data)),
|
||||
/** POST /invites/:code/join (host-pvp, docs/game/HOSTING.md "Seats, invites, quick match and polling"). */
|
||||
joinInvite: (code: string, deck: string[], idToken: string) =>
|
||||
duelCall(`invites/${id(code)}/join`, { body: { deck, idToken } }).then(r => parseSeat(r.data)),
|
||||
quick: (modeId: string, deck: string[], idToken: string) =>
|
||||
duelCall(`modes/${id(modeId)}/quick`, { body: { deck, idToken } }).then(r => parseSeat(r.data)),
|
||||
/** Returns null when the host answers 204 (nothing changed since `version`). */
|
||||
status: (s: DuelSeat, version?: number) =>
|
||||
duelCall(`lobbies/${id(s.lobbyId)}${version ? `?v=${version}` : ''}`, { seat: s.token }).then(r => (r.status === 204 ? null : parseDuelStatus(r.data))),
|
||||
act: (s: DuelSeat, action: unknown) =>
|
||||
duelCall(`lobbies/${id(s.lobbyId)}/actions`, { body: { action }, seat: s.token }).then(r => parseDuelStatus(r.data)),
|
||||
resign: (s: DuelSeat) =>
|
||||
duelCall(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, seat: s.token }).then(r => parseDuelStatus(r.data)),
|
||||
/** Elo ladder; falls back to the W/L leaderboard (cut order 1) when the host has no ladder. */
|
||||
ladder: async (modeId: string): Promise<LadderEntry[]> => {
|
||||
try { return parseLadder((await duelCall(`modes/${id(modeId)}/ladder`)).data); }
|
||||
catch { return parseLadder((await duelCall(`modes/${id(modeId)}/leaderboard`)).data); }
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ArrowLeft, LoaderCircle, Share2 } from 'lucide-react';
|
||||
import { fallbackRecap, parseMatchRecord, runs, type RecapDoc } from './model.ts';
|
||||
|
||||
/** /recap/<matchId> (DUEL_DESIGN §8.3; /battle/<matchId> is accepted as an alias): encyclopedic recap of a finished match, replayed from the host's record. */
|
||||
export function matchIdFromPath(path: string): string {
|
||||
const m = path.match(/^\/(?:battle|recap)\/([A-Za-z0-9_-]{1,128})\/?$/);
|
||||
return m ? m[1] : '';
|
||||
}
|
||||
|
||||
export async function loadRecap(matchId: string, f: typeof fetch = fetch): Promise<RecapDoc> {
|
||||
const res = await f(`/api/game/matches/${encodeURIComponent(matchId)}`, { cache: 'no-store', signal: AbortSignal.timeout(10000) });
|
||||
if (res.status === 404) throw new Error('No battle is recorded under this link.');
|
||||
if (!res.ok || !res.headers.get('content-type')?.includes('json')) throw new Error(`The host answered ${res.status}.`);
|
||||
return fallbackRecap(parseMatchRecord(await res.json()));
|
||||
}
|
||||
|
||||
function Text({ src }: { src: string }) {
|
||||
return <>{runs(src).map((r, i) => r.cite ? <sup key={i} className="recap-cite"><a href={`#ref-${r.cite}`}>{r.text}</a></sup>
|
||||
: r.bold ? <b key={i}>{r.text}</b> : r.italic ? <i key={i}>{r.text}</i> : <span key={i}>{r.text}</span>)}</>;
|
||||
}
|
||||
const revLink = (url: string, rev?: number) => (rev ? `${url}${url.includes('?') ? '&' : '?'}oldid=${rev}` : url);
|
||||
const safe = (url: string) => (/^https:\/\/[a-z]+\.wikipedia\.org\//i.test(url) ? url : '');
|
||||
|
||||
/** Renders a RecapDoc from shared/duel/story (or the local fallback). WikiDeck masthead, not Wikipedia's. */
|
||||
export function RecapArticle({ doc }: { doc: RecapDoc }) {
|
||||
const ib = doc.infobox;
|
||||
const pair = (label: string, v: [string, string]) => <>
|
||||
<tr className="ib-section"><th colSpan={2}>{label}</th></tr>
|
||||
<tr><td>{v[0]}</td><td>{v[1]}</td></tr></>;
|
||||
return <article className="recap" aria-labelledby="recap-title">
|
||||
<header className="recap-head">
|
||||
<div className="recap-brand">{doc.masthead} · Battle record</div>
|
||||
<h1 id="recap-title">{doc.title}</h1>
|
||||
<p className="recap-from">From WikiDeck, the free card game</p>
|
||||
</header>
|
||||
<aside className="recap-infobox" aria-label="Infobox">
|
||||
<div className="ib-title">{doc.title}</div>
|
||||
<table><tbody>
|
||||
<tr><th>Date</th><td>{ib.date}</td></tr>
|
||||
<tr><th>Location</th><td>{ib.location}</td></tr>
|
||||
<tr><th>Result</th><td>{ib.result}</td></tr>
|
||||
{pair('Belligerents', ib.belligerents)}
|
||||
{pair('Commanders', ib.commanders)}
|
||||
{pair('Strength', ib.strength)}
|
||||
{pair('Casualties', ib.casualties)}
|
||||
</tbody></table>
|
||||
</aside>
|
||||
<p><Text src={doc.lead} /></p>
|
||||
{doc.sections.map(s => <section key={s.heading}>
|
||||
<h2>{s.heading}</h2>
|
||||
{s.paragraphs.map((p, i) => <p key={i}><Text src={p} /></p>)}
|
||||
</section>)}
|
||||
{doc.references.length > 0 && <section className="recap-refs" aria-labelledby="refs-title">
|
||||
<h2 id="refs-title">References</h2>
|
||||
<ol>{doc.references.map(r => { const url = safe(r.url); return <li key={r.n} id={`ref-${r.n}`}>
|
||||
{url ? <a href={revLink(url, r.revisionId)} target="_blank" rel="noopener noreferrer">“{r.title}”</a> : <>“{r.title}”</>}
|
||||
. <i>Wikipedia</i>{r.revisionId ? `, revision ${r.revisionId}` : ''}{r.tokenId ? `. Card ${r.tokenId.slice(0, 12)}` : ''}.
|
||||
</li>; })}</ol>
|
||||
</section>}
|
||||
<footer className="recap-footer">{doc.footer}</footer>
|
||||
</article>;
|
||||
}
|
||||
|
||||
export function BattleRecap({ matchId, onExit }: { matchId: string; onExit: () => void }) {
|
||||
const [doc, setDoc] = useState<RecapDoc>();
|
||||
const [error, setError] = useState('');
|
||||
const [note, setNote] = useState('');
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
loadRecap(matchId).then(d => { if (active) { setDoc(d); document.title = `${d.title} · WikiDeck`; } },
|
||||
e => { if (active) setError(e instanceof Error ? e.message : 'The host is unreachable.'); });
|
||||
return () => { active = false; };
|
||||
}, [matchId]);
|
||||
const share = async () => {
|
||||
const url = `${location.origin}/recap/${encodeURIComponent(matchId)}`;
|
||||
try {
|
||||
if (navigator.share) await navigator.share({ title: doc?.title ?? 'WikiDeck battle', url });
|
||||
else { await navigator.clipboard.writeText(url); setNote('Link copied.'); }
|
||||
} catch { setNote(url); }
|
||||
};
|
||||
return <section className="play-panel recap-page">
|
||||
<div className="recap-tools">
|
||||
<button className="button outline" onClick={onExit}><ArrowLeft size={16} /> WikiDeck</button>
|
||||
<button className="button outline" onClick={share} disabled={!doc}><Share2 size={16} /> Share</button>
|
||||
</div>
|
||||
{note && <p className="muted small" role="status">{note}</p>}
|
||||
{error ? <p className="dock-error" role="alert">{error}</p>
|
||||
: doc ? <RecapArticle doc={doc} />
|
||||
: <p className="muted"><LoaderCircle className="spin" size={14} /> Loading the battle record…</p>}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// Battle recap view model ("Battle of X (2026)", BRIEF "Story"). The page renders a RecapDoc. The
|
||||
// authoritative generator is duel-design's shared/duel/story (deterministic templates over the real
|
||||
// match log); until it is on the branch, `fallbackRecap` builds a plain doc from the stored match
|
||||
// record using only real card and match data: no prose beyond fixed templates, no invented facts.
|
||||
|
||||
/**
|
||||
* Mirror of duel-design's `RecapDoc` (shared/duel/story/recap.ts, PR #69), so the page renders either
|
||||
* generator's output. Text fields use the story markup: **bold**, *italic* and [n] citation markers.
|
||||
*/
|
||||
export type RecapReference = { n: number; title: string; url: string; revisionId?: number; tokenId?: string; text?: string };
|
||||
export type RecapDoc = {
|
||||
matchId: string; url: string; masthead: 'WikiDeck'; title: string;
|
||||
infobox: { date: string; location: string; result: string; belligerents: [string, string]; commanders: [string, string];
|
||||
strength: [string, string]; casualties: [string, string] };
|
||||
lead: string; sections: { heading: string; paragraphs: string[] }[]; references: RecapReference[]; footer: string;
|
||||
};
|
||||
export const FOOTER = 'This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events.';
|
||||
|
||||
/** Split story markup into plain, bold, italic and citation runs (rendered as React text, never HTML). */
|
||||
export type Run = { text: string; bold?: boolean; italic?: boolean; cite?: number };
|
||||
export function runs(src: string): Run[] {
|
||||
const out: Run[] = [];
|
||||
const re = /\*\*([^*]+)\*\*|\*([^*]+)\*|\[(\d{1,4})\]/g;
|
||||
let last = 0;
|
||||
for (let m: RegExpExecArray | null; (m = re.exec(src));) {
|
||||
if (m.index > last) out.push({ text: src.slice(last, m.index) });
|
||||
if (m[1] !== undefined) out.push({ text: m[1], bold: true });
|
||||
else if (m[2] !== undefined) out.push({ text: m[2], italic: true });
|
||||
else out.push({ text: `[${m[3]}]`, cite: Number(m[3]) });
|
||||
last = m.index + m[0].length;
|
||||
}
|
||||
if (last < src.length) out.push({ text: src.slice(last) });
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Match record as stored by the host (GET /api/game/matches/:id). Every field is untrusted. */
|
||||
export type MatchCardRef = { tokenId?: string; pageId: number; title: string; revisionId?: number; url?: string; type?: string };
|
||||
export type MatchRecord = {
|
||||
matchId: string; modeId?: string; modeName?: string;
|
||||
players: [string, string]; startedAt?: number; endedAt?: number;
|
||||
winner: 0 | 1 | null; reason?: string; turns?: number;
|
||||
/** Deck sizes or cards brought, per seat. */
|
||||
strength?: [number, number];
|
||||
/** Cards each seat played, in order (real cards from the chain). */
|
||||
played?: [MatchCardRef[], MatchCardRef[]];
|
||||
/** Cards each seat lost (destroyed / sent to the graveyard). */
|
||||
lost?: [MatchCardRef[], MatchCardRef[]];
|
||||
/** Public, past-tense log lines (host's spectator/public logFor). */
|
||||
log?: { turn: number; text: string }[];
|
||||
/** Raw record, kept for the shared generator (replay needs seed + actions). */
|
||||
raw: unknown;
|
||||
};
|
||||
|
||||
const str = (v: unknown, max = 200) => (typeof v === 'string' ? v.slice(0, max) : '');
|
||||
const int = (v: unknown) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : undefined);
|
||||
const wikiUrl = (title: string) => `https://en.wikipedia.org/wiki/${encodeURIComponent(title.replace(/ /g, '_'))}`;
|
||||
const safeUrl = (v: unknown) => { const s = str(v, 2000); return /^https:\/\/[a-z]+\.wikipedia\.org\//i.test(s) ? s : undefined; };
|
||||
|
||||
function cardRef(v: unknown): MatchCardRef | undefined {
|
||||
if (!v || typeof v !== 'object') return undefined;
|
||||
const o = v as Record<string, unknown>;
|
||||
const card = (o.card && typeof o.card === 'object' ? o.card : o) as Record<string, unknown>;
|
||||
const pageId = int(card.pageId), title = str(card.title, 200);
|
||||
if (!pageId || !title) return undefined;
|
||||
return { pageId, title, tokenId: str(card.tokenId ?? card.cardId, 128) || undefined, revisionId: int(card.revisionId),
|
||||
url: safeUrl(card.url), type: str(card.type, 30) || undefined };
|
||||
}
|
||||
const refs = (v: unknown): MatchCardRef[] => (Array.isArray(v) ? v.slice(0, 200).map(cardRef).filter((c): c is MatchCardRef => !!c) : []);
|
||||
const pair = <T,>(v: unknown, f: (x: unknown) => T): [T, T] | undefined => (Array.isArray(v) && v.length === 2 ? [f(v[0]), f(v[1])] : undefined);
|
||||
|
||||
export function parseMatchRecord(v: unknown): MatchRecord {
|
||||
const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
|
||||
const r = (o.result && typeof o.result === 'object' ? o.result : o) as Record<string, unknown>;
|
||||
const names = (Array.isArray(o.players) ? o.players : []).slice(0, 2).map((p, i) =>
|
||||
str(typeof p === 'string' ? p : (p as Record<string, unknown> | null)?.name, 24) || `Player ${i + 1}`);
|
||||
while (names.length < 2) names.push(`Player ${names.length + 1}`);
|
||||
const winner = r.winner === 0 || r.winner === 1 ? r.winner : null;
|
||||
const log = Array.isArray(o.log) ? o.log.slice(0, 2000).flatMap(e => {
|
||||
if (typeof e === 'string') return [{ turn: 0, text: e.slice(0, 400) }];
|
||||
const x = (e && typeof e === 'object' ? e : {}) as Record<string, unknown>;
|
||||
const text = str(x.text, 400);
|
||||
return text ? [{ turn: int(x.turn) ?? 0, text }] : [];
|
||||
}) : undefined;
|
||||
return {
|
||||
matchId: str(o.matchId ?? o.id, 128), modeId: str(o.modeId, 64) || undefined, modeName: str(o.modeName, 64) || undefined,
|
||||
players: [names[0], names[1]], startedAt: int(o.startedAt), endedAt: int(o.endedAt ?? o.finishedAt), winner,
|
||||
reason: str(r.reason, 60) || undefined, turns: int(o.turns ?? r.turns),
|
||||
// host-pvp records carry `decks` (engine cards per seat); their sizes are each side's strength.
|
||||
strength: pair(o.strength, x => int(x) ?? 0) ?? pair(o.decks, x => (Array.isArray(x) ? x.length : 0)), played: pair(o.played, refs), lost: pair(o.lost, refs), log, raw: v,
|
||||
};
|
||||
}
|
||||
|
||||
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
export const longDate = (ms: number) => { const d = new Date(ms); return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`; };
|
||||
const NUMBERS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve'];
|
||||
const spell = (n: number) => NUMBERS[n] ?? String(n);
|
||||
const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`;
|
||||
|
||||
/** Stable 32-bit hash for deterministic template choice. */
|
||||
export function seedOf(s: string): number { let h = 2166136261; for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return h >>> 0; }
|
||||
const pick = <T,>(list: T[], seed: number, salt: number) => list[(seed + salt * 2654435761) % list.length >>> 0];
|
||||
|
||||
/** Fallback generator (until shared/duel/story merges): fixed templates over real data only (BRIEF decision 5). */
|
||||
export function fallbackRecap(m: MatchRecord): RecapDoc {
|
||||
const seed = seedOf(m.matchId || 'match');
|
||||
const when = m.endedAt ?? m.startedAt;
|
||||
const date = when ? longDate(when) : 'an unrecorded date';
|
||||
const year = when ? new Date(when).getUTCFullYear() : undefined;
|
||||
const all = [...(m.played?.[0] ?? []), ...(m.played?.[1] ?? [])];
|
||||
// Card titles are data: strip story markup characters so a title can't restyle the page.
|
||||
const t = (c: MatchCardRef) => `*${c.title.replace(/[*[\]]/g, '')}*`;
|
||||
|
||||
// References: every card played, deduplicated by pageId+revision, numbered in order of first appearance.
|
||||
const references: RecapReference[] = [];
|
||||
const refNo = new Map<string, number>();
|
||||
const cite = (c: MatchCardRef) => {
|
||||
const key = `${c.pageId}:${c.revisionId ?? ''}`;
|
||||
let n = refNo.get(key);
|
||||
if (!n) { n = references.length + 1; refNo.set(key, n); references.push({ n, title: c.title, revisionId: c.revisionId, tokenId: c.tokenId, url: c.url ?? wikiUrl(c.title) }); }
|
||||
return `[${n}]`;
|
||||
};
|
||||
|
||||
// Named after the decisive non-Figure card (the winner's last non-Figure played), else the date.
|
||||
const winnerPlayed = m.winner === null ? all : m.played?.[m.winner] ?? [];
|
||||
const namesake = [...winnerPlayed].reverse().find(c => c.type && !/figure/i.test(c.type)) ?? [...winnerPlayed].reverse()[0];
|
||||
const bare = namesake ? `Battle of ${namesake.title.replace(/[*[\]]/g, '')}` : `Match of ${date}`;
|
||||
const title = namesake && year ? `${bare} (${year})` : bare;
|
||||
|
||||
const [a, b] = m.players;
|
||||
const ending = m.winner === null ? 'in a draw' : `in a victory for ${m.players[m.winner]}`;
|
||||
let lead = `The **${bare}** was a WikiDeck engagement fought on ${date} between the forces of ${a} and ${b}.`;
|
||||
lead += m.turns ? ` It lasted ${spell(m.turns)} turns and ended ${ending}.` : ` It ended ${ending}.`;
|
||||
if (namesake) lead += cite(namesake);
|
||||
|
||||
const course: string[] = [];
|
||||
const opener = ['Contemporary accounts note the deployment of ', 'Sources describe the early commitment of ', 'The engagement opened with '];
|
||||
for (const seat of [0, 1] as const) {
|
||||
const cards = m.played?.[seat] ?? [];
|
||||
if (!cards.length) continue;
|
||||
let p = `${pick(opener, seed, seat + 1)}${t(cards[0])}${cite(cards[0])} by ${m.players[seat]}.`;
|
||||
const rest = cards.slice(1, 4);
|
||||
if (rest.length) p += ` ${m.players[seat]} later committed ${rest.map((c, i) => `${t(c)}${cite(c)}${i === rest.length - 1 ? '' : i === rest.length - 2 ? ' and' : ','}`).join(' ')}.`;
|
||||
course.push(p);
|
||||
}
|
||||
for (const c of all) cite(c);
|
||||
if (m.reason && m.winner !== null) course.push(`${m.players[1 - m.winner]} ${reasonText(m.reason)}.`);
|
||||
const aftermath: string[] = [];
|
||||
if (m.lost) {
|
||||
const n = m.lost[0].length + m.lost[1].length;
|
||||
aftermath.push(n ? `In total ${plural(n, 'card')} were destroyed: ${m.lost[0].length} from ${a} and ${m.lost[1].length} from ${b}.` : 'No cards were destroyed.');
|
||||
}
|
||||
|
||||
const strength = (i: 0 | 1) => (m.strength ? plural(m.strength[i], 'card') : m.played ? `${plural(m.played[i].length, 'card')} played` : 'Unknown');
|
||||
const casualties = (i: 0 | 1) => (!m.lost ? 'Unknown' : m.lost[i].length ? `${plural(m.lost[i].length, 'card')} destroyed: ${m.lost[i].map(c => c.title).join(', ')}` : 'None');
|
||||
const commander = (i: 0 | 1) => m.played?.[i].find(c => /figure/i.test(c.type ?? ''))?.title ?? 'None recorded';
|
||||
const sections = [{ heading: 'Course of the battle', paragraphs: course }, { heading: 'Aftermath', paragraphs: aftermath }].filter(x => x.paragraphs.length);
|
||||
return { matchId: m.matchId, url: `/recap/${m.matchId}`, masthead: 'WikiDeck', title, lead, sections, references, footer: FOOTER,
|
||||
infobox: { date, location: m.modeName ? `WikiDeck · ${m.modeName}` : 'WikiDeck', result: m.winner === null ? 'Draw' : `Victory for ${m.players[m.winner]}`,
|
||||
belligerents: [a, b], commanders: [commander(0), commander(1)], strength: [strength(0), strength(1)], casualties: [casualties(0), casualties(1)] } };
|
||||
}
|
||||
|
||||
function reasonText(r: string): string {
|
||||
switch (r) {
|
||||
case 'notability': case 'life': return 'was reduced to zero Notability';
|
||||
case 'library': case 'decked': return 'could not draw from an empty library';
|
||||
case 'resign': case 'concede': return 'withdrew from the engagement';
|
||||
case 'timeout': case 'afk': return 'did not act before the clock expired';
|
||||
default: return `lost (${r})`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/* Battle recap: encyclopedic texture, WikiDeck branding (serif headline, infobox), 360 px first. */
|
||||
.recap-page{max-width:880px}
|
||||
.recap-tools{display:flex;justify-content:space-between;gap:8px;margin-bottom:12px}
|
||||
.recap-tools .button{min-height:40px;font-size:13px;padding:8px 12px}
|
||||
.recap{font-size:15px;line-height:1.65;color:var(--ctp-text);padding-bottom:24px}
|
||||
.recap::after{content:"";display:block;clear:both}
|
||||
.recap-head{border-bottom:1px solid var(--theme-border);margin-bottom:12px;padding-bottom:6px}
|
||||
.recap-brand{font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--ctp-mauve);font-weight:700}
|
||||
.recap h1{font-family:Georgia,'Times New Roman',serif;font-weight:400;font-size:28px;line-height:1.2;margin:4px 0 2px;letter-spacing:0}
|
||||
.recap-from{font-size:12px;color:var(--ctp-subtext0);margin:0}
|
||||
.recap p{margin:0 0 12px}
|
||||
.recap i{font-style:italic}
|
||||
.recap-cite{font-size:11px;line-height:0}
|
||||
.recap-cite a{color:var(--ctp-blue);text-decoration:none}
|
||||
.recap-infobox{border:1px solid var(--theme-border);background:var(--ctp-base);border-radius:8px;padding:8px;margin:0 0 14px;font-size:13px}
|
||||
.recap-infobox .ib-title{font-weight:700;text-align:center;background:var(--ctp-surface0);border-radius:4px;padding:6px;margin-bottom:6px}
|
||||
.recap-infobox table{width:100%;border-collapse:collapse;table-layout:fixed}
|
||||
.recap-infobox th,.recap-infobox td{padding:4px 6px;vertical-align:top;text-align:left;overflow-wrap:anywhere}
|
||||
.recap-infobox th{width:38%;color:var(--ctp-subtext1);font-weight:600}
|
||||
.recap-infobox .ib-section th{text-align:center;background:var(--ctp-surface0);color:var(--ctp-text);width:auto}
|
||||
.recap-refs h2{font-family:Georgia,'Times New Roman',serif;font-weight:400;font-size:20px;border-bottom:1px solid var(--theme-border);margin:20px 0 8px}
|
||||
.recap-refs ol{padding-left:22px;font-size:13px}
|
||||
.recap-refs li:target{background:var(--ctp-surface0)}
|
||||
.recap-refs a{color:var(--ctp-blue)}
|
||||
@media (min-width:640px){.recap-infobox{float:right;width:300px;margin:0 0 14px 18px}}
|
||||
.recap-shell{min-height:100vh;padding:16px 12px;background:var(--ctp-base)}
|
||||
.recap section>h2{font-family:Georgia,'Times New Roman',serif;font-weight:400;font-size:20px;border-bottom:1px solid var(--theme-border);margin:18px 0 8px}
|
||||
.recap-footer{clear:both;margin-top:20px;padding-top:10px;border-top:1px solid var(--theme-border);font-size:11px;color:var(--ctp-subtext0)}
|
||||
.recap-infobox td,.recap-infobox th{white-space:normal;word-break:break-word}
|
||||
@@ -0,0 +1,88 @@
|
||||
// Playwright smoke test for the ui-pvp screens (not part of `npm test`: Playwright isn't a repo dependency).
|
||||
// Every /api call is stubbed in the browser, so it makes zero network calls beyond localhost.
|
||||
// Run: npm run build && npx vite preview --port 4179 & then
|
||||
// PLAYWRIGHT_FROM=<dir containing node_modules/playwright>/ node tests/e2e/ui-pvp-smoke.mjs http://localhost:4179 <out-dir>
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFileSync, mkdirSync } from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const { chromium } = createRequire(process.env.PLAYWRIGHT_FROM ? `${process.env.PLAYWRIGHT_FROM.replace(/\/?$/, '/')}x.js` : import.meta.url)('playwright');
|
||||
const base = process.argv[2] ?? 'http://localhost:4179';
|
||||
const out = process.argv[3] ?? 'screenshots';
|
||||
mkdirSync(out, { recursive: true });
|
||||
const sample = JSON.parse(readFileSync(new URL('../../docs/game/card-sample.json', import.meta.url), 'utf8')).cards;
|
||||
const cards = n => sample.slice(0, n).map((c, i) => ({ tokenId: `tok${i}`, pageId: c.pageId, title: c.title, revisionId: c.revisionId,
|
||||
url: `https://en.wikipedia.org/wiki/${encodeURIComponent(c.title.replace(/ /g, '_'))}`, category: 'People', height: 10 + i, confirmations: 3 }));
|
||||
const account = { sub: 'alice-sub', issuer: 'https://dex.eom.dev', name: 'alice', username: 'alice', wallets: [{ address: 'a'.repeat(64), linkedAt: 1 }] };
|
||||
const match = { matchId: 'm_smoke', modeName: 'Classic', players: [{ name: 'alice' }, { name: 'bob' }], turns: 9,
|
||||
startedAt: Date.UTC(2026, 10, 17, 23, 40), endedAt: Date.UTC(2026, 10, 18, 0, 2), result: { winner: 0, reason: 'notability' }, strength: [40, 40],
|
||||
played: [sample.slice(0, 4).map(c => ({ ...c, type: 'Figure' })).concat([{ ...sample[10], type: 'Doctrine' }]), sample.slice(4, 8).map(c => ({ ...c, type: 'Figure' }))],
|
||||
lost: [[sample[1]], [sample[4], sample[5]]] };
|
||||
|
||||
async function page(browser, { width, height, owned }) {
|
||||
const ctx = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: 2 });
|
||||
await ctx.addInitScript(a => {
|
||||
sessionStorage.setItem('wikideck.auth.session', JSON.stringify({ idToken: 'test-token', expiresAt: Date.now() + 3600e3, account: a }));
|
||||
localStorage.setItem('wikideck-play-tutorial-v1', '1');
|
||||
}, account);
|
||||
let lobbyPolls = 0;
|
||||
await ctx.route('**/api/**', async route => {
|
||||
const url = new URL(route.request().url());
|
||||
const p = url.pathname, json = (body, status = 200) => route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });
|
||||
if (p === '/api/game/collection') return json({ deckSize: 40, copyLimit: 4, cards: cards(owned) });
|
||||
if (p === '/api/account/me') return json(account);
|
||||
if (p === '/api/game/modes') return json({ modes: [{ mode: { id: 'classic', name: 'Classic', engine: 'duel', limits: { rated: true } } }] });
|
||||
if (p.endsWith('/ladder')) return json({ entries: [{ name: 'alice', rating: 1236, wins: 4, losses: 1 }, { name: 'bob', rating: 1188, wins: 1, losses: 3 }, { name: 'carol', rating: 1176, wins: 0, losses: 1 }] });
|
||||
if (p === '/api/game/modes/classic/lobbies') return json({ lobbyId: 'L1', seat: 0, token: 'seat-tok', invite: 'Inv7Qx2' });
|
||||
if (p === '/api/game/lobbies/L1') { lobbyPolls++; return json({ lobbyId: 'L1', version: 1, phase: 'waiting', seat: 0, players: [{ name: 'alice' }], outcome: null, invite: 'Inv7Qx2' }); }
|
||||
if (p === '/api/game/matches/m_smoke') return json(match);
|
||||
return route.fulfill({ status: 503, contentType: 'application/json', body: '{"error":"stubbed"}' });
|
||||
});
|
||||
return { ctx, page: await ctx.newPage(), polls: () => lobbyPolls };
|
||||
}
|
||||
const openPlay = async p => {
|
||||
await p.goto(base + '/');
|
||||
await p.getByRole('navigation', { name: 'Main navigation' }).getByText('Play', { exact: true }).first().click();
|
||||
};
|
||||
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
// 1. Under 40 cards: progress + mine, no borrowed decks.
|
||||
{ const { ctx, page: p } = await page(browser, { width: 360, height: 740, owned: 23 });
|
||||
await openPlay(p);
|
||||
await p.getByText('23 / 40 cards. Mine to play').waitFor();
|
||||
assert.equal(await p.getByRole('button', { name: /Quick match/ }).count(), 0, 'no play buttons below 40 cards');
|
||||
assert.equal(await p.getByText(/loaner|starter deck/i).count(), 0, 'no loaners offered');
|
||||
await p.screenshot({ path: `${out}/1-eligibility-360.png`, fullPage: true }); await ctx.close(); }
|
||||
// 2. 44 cards: PvP hub with quick match, private lobby, join, ladder.
|
||||
{ const { ctx, page: p, polls } = await page(browser, { width: 360, height: 740, owned: 44 });
|
||||
await openPlay(p);
|
||||
await p.getByRole('button', { name: /Quick match/ }).waitFor();
|
||||
await p.getByText('40 / 40').waitFor();
|
||||
await p.getByText('1236').waitFor();
|
||||
await p.screenshot({ path: `${out}/2-pvp-hub-360.png`, fullPage: true });
|
||||
await p.getByRole('button', { name: 'Edit deck' }).click();
|
||||
await p.getByText(/Pick exactly 40/).waitFor();
|
||||
await p.screenshot({ path: `${out}/3-deck-picker-360.png` });
|
||||
await p.getByRole('button', { name: 'Cancel' }).click();
|
||||
await p.getByRole('button', { name: /Private lobby/ }).click();
|
||||
await p.getByLabel('Invite link').getByText(/\/play\/invite\/Inv7Qx2$/).waitFor();
|
||||
await p.waitForTimeout(2500);
|
||||
assert.ok(polls() >= 1, 'the lobby polls the host');
|
||||
await p.screenshot({ path: `${out}/4-private-lobby-360.png`, fullPage: true }); await ctx.close(); }
|
||||
// 3. Invite deep link.
|
||||
{ const { ctx, page: p } = await page(browser, { width: 360, height: 740, owned: 44 });
|
||||
await p.goto(base + '/play/invite/Inv7Qx2');
|
||||
await p.getByText('You have been invited to a duel.').waitFor();
|
||||
await p.screenshot({ path: `${out}/5-invite-360.png` }); await ctx.close(); }
|
||||
// 4. Battle recap at 360 and desktop.
|
||||
for (const [w, h, name] of [[360, 740, '6-recap-360'], [1280, 900, '7-recap-desktop']]) {
|
||||
const { ctx, page: p } = await page(browser, { width: w, height: h, owned: 44 });
|
||||
await p.goto(base + (w === 360 ? '/recap/m_smoke' : '/battle/m_smoke'));
|
||||
await p.getByRole('heading', { level: 1, name: /^Battle of / }).waitFor();
|
||||
await p.getByRole('heading', { name: 'References' }).waitFor();
|
||||
assert.ok(await p.locator('.recap-refs li').count() >= 8);
|
||||
await p.screenshot({ path: `${out}/${name}.png`, fullPage: true }); await ctx.close();
|
||||
}
|
||||
console.log('ui-pvp smoke: OK');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,99 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { collectionFromBlocks, deckProblem, eligibility, fillDeck, parseCollection, playableCount, progressLabel, type Collection } from '../src/game/collection/collection.ts';
|
||||
import { CLASSIC, parseDuelModes } from '../src/game/collection/duelModes.ts';
|
||||
import { inviteCode, inviteFromPath, parseDuelStatus, parseLadder, parseSeat } from '../src/game/online.ts';
|
||||
import type { TestnetBlock } from '../shared/testnet.ts';
|
||||
|
||||
const card = (i: number, pageId = 1000 + i) => ({ tokenId: `t${i}`, pageId, title: `Article ${pageId}` });
|
||||
const coll = (n: number, pages?: (i: number) => number, deckSize = 40): Collection =>
|
||||
({ deckSize, copyLimit: 4, source: 'server', cards: Array.from({ length: n }, (_, i) => card(i, pages?.(i))) });
|
||||
|
||||
test('23 owned cards: not eligible, shows "23 / 40 cards" and needs 17 more', () => {
|
||||
const e = eligibility(coll(23));
|
||||
assert.equal(e.eligible, false);
|
||||
assert.equal(e.needed, 17);
|
||||
assert.equal(progressLabel(e), '23 / 40 cards');
|
||||
});
|
||||
|
||||
test('40 owned distinct cards are eligible; the copy limit caps playable cards per article', () => {
|
||||
assert.equal(eligibility(coll(40)).eligible, true);
|
||||
// 44 cards over 10 articles: at most 4 copies each → 40 playable.
|
||||
assert.equal(playableCount(coll(44, i => i % 10)), 40);
|
||||
// 50 cards of 5 articles: only 20 playable, so not eligible despite owning 50.
|
||||
const e = eligibility(coll(50, i => i % 5));
|
||||
assert.equal(e.owned, 50);
|
||||
assert.equal(e.playable, 20);
|
||||
assert.equal(e.eligible, false);
|
||||
});
|
||||
|
||||
test('deckProblem: exactly deckSize owned cards, no repeats, copy limit enforced', () => {
|
||||
const c = coll(60, i => (i < 8 ? 1 : 1000 + i));
|
||||
const legal = fillDeck([], c);
|
||||
assert.equal(legal.length, 40);
|
||||
assert.equal(deckProblem(legal, c), '');
|
||||
assert.match(deckProblem(legal.slice(1), c), /exactly 40/);
|
||||
assert.match(deckProblem([...legal.slice(1), 'not-mine'], c), /no longer own/);
|
||||
assert.match(deckProblem([...legal.slice(1), legal[2]], c), /twice/);
|
||||
const fiveCopies = [...c.cards.slice(0, 5).map(x => x.tokenId), ...c.cards.slice(8, 43).map(x => x.tokenId)];
|
||||
assert.match(deckProblem(fiveCopies, c), /At most 4 copies/);
|
||||
});
|
||||
|
||||
test('fillDeck keeps still-owned saved cards first and drops sold ones', () => {
|
||||
const c = coll(45);
|
||||
const deck = fillDeck(['t44', 'gone', 't43'], c);
|
||||
assert.deepEqual(deck.slice(0, 2), ['t44', 't43']);
|
||||
assert.equal(deck.length, 40);
|
||||
assert.ok(!deck.includes('gone'));
|
||||
});
|
||||
|
||||
test('a testnet mode may lower deckSize; production default stays 40', () => {
|
||||
assert.equal(parseCollection({}).deckSize, 40);
|
||||
assert.equal(eligibility(coll(12, undefined, 10)).eligible, true);
|
||||
});
|
||||
|
||||
test('parseCollection drops malformed cards, duplicate tokenIds and non-https urls', () => {
|
||||
const c = parseCollection({ deckSize: 40, copyLimit: 4, cards: [
|
||||
{ tokenId: 'a', pageId: 5, title: 'Five', url: 'javascript:alert(1)', imageUrl: 'https://upload.wikimedia.org/x.jpg' },
|
||||
{ tokenId: 'a', pageId: 6, title: 'Dup' }, { tokenId: 'b' }, null, 'x', { tokenId: 'c', pageId: -1 },
|
||||
] });
|
||||
assert.equal(c.cards.length, 1);
|
||||
assert.equal(c.cards[0].url, undefined);
|
||||
assert.equal(c.cards[0].imageUrl, 'https://upload.wikimedia.org/x.jpg');
|
||||
});
|
||||
|
||||
test('the local fallback reads real owned blocks only', () => {
|
||||
const block = { tokenId: 'tok', height: 7, article: { pageId: 9, title: 'Nine', revisionId: 3, url: 'https://en.wikipedia.org/wiki/Nine', extract: 'x', category: 'Places', source: 'live' } } as unknown as TestnetBlock;
|
||||
const c = collectionFromBlocks([block]);
|
||||
assert.equal(c.source, 'local');
|
||||
assert.deepEqual(c.cards.map(x => [x.tokenId, x.pageId, x.height]), [['tok', 9, 7]]);
|
||||
});
|
||||
|
||||
test('invite links: parse a pasted URL, a bare code, and the deep link path', () => {
|
||||
assert.equal(inviteCode('https://wikideck.eom.dev/play/invite/AbC_123'), 'AbC_123');
|
||||
assert.equal(inviteCode(' AbC_123 '), 'AbC_123');
|
||||
assert.equal(inviteCode('https://evil.example/<script>'), '');
|
||||
assert.equal(inviteFromPath('/play/invite/xyz9'), 'xyz9');
|
||||
assert.equal(inviteFromPath('/play/join/lob_1'), 'lob_1');
|
||||
assert.equal(inviteFromPath('/battle/abc'), '');
|
||||
});
|
||||
|
||||
test('host responses are validated: seats, statuses and the ladder', () => {
|
||||
assert.deepEqual(parseSeat({ lobbyId: 'L1', seat: 1, token: 'tok', invite: 'inv1' }), { lobbyId: 'L1', seat: 1, token: 'tok', invite: 'inv1' });
|
||||
assert.throws(() => parseSeat({ lobbyId: 'L1', seat: 2, token: 'tok' }), /invalid seat/);
|
||||
const s = parseDuelStatus({ lobbyId: 'L1', version: 4, phase: 'bogus', players: [{ name: 'x'.repeat(99), rating: 1211.6 }], matchId: '../etc' });
|
||||
assert.equal(s.phase, 'waiting');
|
||||
assert.equal(s.players[0].name.length, 24);
|
||||
assert.equal(s.players[0].rating, 1212);
|
||||
assert.equal(s.matchId, undefined);
|
||||
const l = parseLadder({ entries: [{ name: 'alice', rating: 1224, wins: 3, losses: 1 }, { name: '', wins: -2 }, 7] });
|
||||
assert.deepEqual(l, [{ name: 'alice', rating: 1224, wins: 3, losses: 1, draws: 0 }, { name: 'Anonymous', rating: null, wins: 0, losses: 0, draws: 0 }]);
|
||||
});
|
||||
|
||||
test('only duel-engine modes are offered; Classic is the default', () => {
|
||||
assert.equal(CLASSIC.id, 'classic');
|
||||
const m = parseDuelModes({ modes: [{ mode: { id: 'standard', name: 'Edit War', engine: 'editwar' } },
|
||||
{ mode: { id: 'classic', name: 'Classic', engine: 'duel', limits: { rated: true } } },
|
||||
{ mode: { id: 'e2e', name: 'Testnet E2E', engine: 'duel', rules: { deckSize: 20 } } }] });
|
||||
assert.deepEqual(m.map(x => [x.id, x.ranked, x.deckSize]), [['classic', true, undefined], ['e2e', false, 20]]);
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { createElement } from 'react';
|
||||
import { RecapArticle, loadRecap, matchIdFromPath } from '../src/game/recap/BattleRecap.tsx';
|
||||
import { fallbackRecap, parseMatchRecord, runs } from '../src/game/recap/model.ts';
|
||||
|
||||
// Real cards from the sample pool (no network).
|
||||
const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8'));
|
||||
const pool: { pageId: number; title: string; revisionId?: number }[] = (Array.isArray(sample) ? sample : sample.cards ?? []).map((c: Record<string, unknown>) => {
|
||||
const a = (c.article ?? c) as Record<string, unknown>;
|
||||
return { pageId: a.pageId as number, title: a.title as string, revisionId: a.revisionId as number | undefined };
|
||||
}).filter((c: { pageId: unknown; title: unknown }) => typeof c.pageId === 'number' && typeof c.title === 'string');
|
||||
|
||||
const record = {
|
||||
matchId: 'm_7f3a', modeName: 'Classic', players: [{ name: 'alice' }, { name: 'bob' }],
|
||||
startedAt: Date.UTC(2026, 10, 17, 23, 40), endedAt: Date.UTC(2026, 10, 18, 0, 2), turns: 9,
|
||||
result: { winner: 0, reason: 'notability' }, strength: [40, 40],
|
||||
played: [pool.slice(0, 4).map(c => ({ ...c, type: 'Figure' })).concat([{ ...pool[4], type: 'Doctrine' }]), pool.slice(5, 8).map(c => ({ ...c, type: 'Figure' }))],
|
||||
lost: [[pool[1]], [pool[5], pool[6]]],
|
||||
};
|
||||
|
||||
test('recap: deterministic, named after the winner’s decisive non-Figure card, with an infobox', () => {
|
||||
assert.ok(pool.length >= 8, 'card-sample.json has cards');
|
||||
const a = fallbackRecap(parseMatchRecord(record));
|
||||
const b = fallbackRecap(parseMatchRecord(structuredClone(record)));
|
||||
assert.deepEqual(a, b);
|
||||
assert.equal(a.title, `Battle of ${pool[4].title} (2026)`);
|
||||
assert.equal(a.infobox.date, '18 November 2026');
|
||||
assert.deepEqual(a.infobox.belligerents, ['alice', 'bob']);
|
||||
assert.deepEqual(a.infobox.casualties, [`1 card destroyed: ${pool[1].title}`, `2 cards destroyed: ${pool[5].title}, ${pool[6].title}`]);
|
||||
assert.deepEqual(a.infobox.commanders, [pool[0].title, pool[5].title]);
|
||||
assert.equal(a.masthead, 'WikiDeck');
|
||||
assert.match(a.footer, /game events/);
|
||||
assert.equal(a.infobox.result, 'Victory for alice');
|
||||
assert.equal(a.url, '/recap/m_7f3a');
|
||||
});
|
||||
|
||||
test('recap: References cite every card played, once each, with revision ids', () => {
|
||||
const doc = fallbackRecap(parseMatchRecord(record));
|
||||
const played = [...record.played[0], ...record.played[1]];
|
||||
assert.equal(doc.references.length, new Set(played.map(c => `${c.pageId}:${c.revisionId ?? ''}`)).size);
|
||||
for (const c of played) assert.ok(doc.references.some(r => r.title === c.title));
|
||||
const html = renderToStaticMarkup(createElement(RecapArticle, { doc }));
|
||||
assert.match(html, /WikiDeck/);
|
||||
assert.match(html, /Casualties/);
|
||||
assert.match(html, /Course of the battle/);
|
||||
assert.doesNotMatch(html, /\*\*/, 'markup is rendered, not shown');
|
||||
assert.match(html, /href="#ref-1"/);
|
||||
if (pool[0].revisionId) assert.match(html, new RegExp(`oldid=${pool[0].revisionId}`));
|
||||
});
|
||||
|
||||
test('recap text: fixed templates only, no adjectives about the outcome or winks', () => {
|
||||
const doc = fallbackRecap(parseMatchRecord(record));
|
||||
const text = [doc.lead, ...doc.sections.flatMap(s => s.paragraphs)].join(' ');
|
||||
assert.doesNotMatch(text, /!|lol|brutal|humiliat|heroic|surprising|twist|killed|decisive|pyrrhic/i);
|
||||
assert.match(text, /\*\*Battle of [^*]+\*\* was a WikiDeck engagement fought on 18 November 2026 between the forces of alice and bob/);
|
||||
assert.match(text, /nine turns/);
|
||||
assert.match(text, /bob was reduced to zero Notability\./);
|
||||
});
|
||||
|
||||
test('recap falls back to "Match of <date>" when nothing was played, and tolerates junk', () => {
|
||||
const doc = fallbackRecap(parseMatchRecord({ matchId: 'x', endedAt: Date.UTC(2026, 10, 17), players: ['a', 'b'], result: { winner: null } }));
|
||||
assert.equal(doc.title, 'Match of 17 November 2026');
|
||||
assert.equal(doc.infobox.result, 'Draw');
|
||||
const junk = fallbackRecap(parseMatchRecord({ players: 7, played: [[{ title: 3 }], 'x'], url: 'javascript:1' }));
|
||||
assert.equal(junk.references.length, 0);
|
||||
});
|
||||
|
||||
test('only https Wikipedia links reach the References', () => {
|
||||
const doc = fallbackRecap(parseMatchRecord({ ...record, played: [[{ pageId: 1, title: 'A', url: 'https://evil.example/a' }], []] }));
|
||||
assert.match(doc.references[0].url, /^https:\/\/en\.wikipedia\.org\/wiki\/A$/);
|
||||
});
|
||||
|
||||
test('/battle/<id> routing and loading from GET /api/game/matches/:id (stubbed fetch)', async () => {
|
||||
assert.equal(matchIdFromPath('/battle/m_7f3a'), 'm_7f3a');
|
||||
assert.equal(matchIdFromPath('/battle/../x'), '');
|
||||
assert.equal(matchIdFromPath('/recap/m_7f3a'), 'm_7f3a');
|
||||
let asked = '';
|
||||
const fake = (async (url: string) => { asked = url; return new Response(JSON.stringify(record), { headers: { 'content-type': 'application/json' } }); }) as typeof fetch;
|
||||
const doc = await loadRecap('m_7f3a', fake);
|
||||
assert.equal(asked, '/api/game/matches/m_7f3a');
|
||||
assert.match(doc.title, /^Battle of /);
|
||||
const missing = (async () => new Response('{}', { status: 404 })) as unknown as typeof fetch;
|
||||
await assert.rejects(loadRecap('nope', missing), /No battle/);
|
||||
});
|
||||
|
||||
test('story markup becomes text runs; card titles cannot inject markup', () => {
|
||||
assert.deepEqual(runs('The **Battle of X** saw *Moon*[2].'), [{ text: 'The ' }, { text: 'Battle of X', bold: true }, { text: ' saw ' },
|
||||
{ text: 'Moon', italic: true }, { text: '[2]', cite: 2 }, { text: '.' }]);
|
||||
const doc = fallbackRecap(parseMatchRecord({ matchId: 'z', players: ['a', 'b'], result: { winner: 0 }, played: [[{ pageId: 1, title: '**Evil** [9]', type: 'Event' }], []] }));
|
||||
assert.equal(doc.title, 'Battle of Evil 9');
|
||||
const seen = [doc.lead, ...doc.sections.flatMap(s => s.paragraphs)].flatMap(runs);
|
||||
assert.ok(!seen.some(r => r.cite === 9));
|
||||
});
|
||||
|
||||
test('a host-pvp match record (winner/reason at top level, decks, no replay yet) still yields a plain recap', () => {
|
||||
const doc = fallbackRecap(parseMatchRecord({ matchId: 'a'.repeat(32), modeId: 'classic', seed: 's', rules: {}, players: [{ id: 'x', name: 'alice' }, { id: 'y', name: 'bob' }],
|
||||
winner: 1, reason: 'concede', startedAt: Date.UTC(2026, 10, 18, 1), endedAt: Date.UTC(2026, 10, 18, 1, 20), decks: [new Array(40).fill({}), new Array(40).fill({})], actions: [] }));
|
||||
assert.equal(doc.title, 'Match of 18 November 2026');
|
||||
assert.equal(doc.infobox.result, 'Victory for bob');
|
||||
assert.deepEqual(doc.infobox.strength, ['40 cards', '40 cards']);
|
||||
assert.match(doc.sections.flatMap(s => s.paragraphs).join(' '), /alice withdrew from the engagement\./);
|
||||
});
|
||||
Reference in New Issue
Block a user