feat(radio): add arena and leaderboard
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
parent
0d58b54977
commit
f71a10ce05
2 changed files with 320 additions and 0 deletions
55
src/components/frontend/radio/RadioArena.tsx
Normal file
55
src/components/frontend/radio/RadioArena.tsx
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import type { RadioStats } from "@/app/(frontend)/radio/actions";
|
||||
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
|
||||
import { RadioLeaderboard } from "./RadioLeaderboard";
|
||||
import { RadioTraffic } from "./RadioTraffic";
|
||||
|
||||
export function RadioArena({
|
||||
initialStats,
|
||||
currentUserId,
|
||||
}: {
|
||||
initialStats: RadioStats;
|
||||
currentUserId: number | string;
|
||||
}) {
|
||||
const [refreshKey, setRefreshKey] = useState(0);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const activeOperators = useRealtimePresence("radio", playing, true);
|
||||
const onPhaseChange = useCallback((phase: "ready" | "playing" | "over") => {
|
||||
setPlaying(phase === "playing");
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-6">
|
||||
<RadioTraffic
|
||||
initialStats={initialStats}
|
||||
onGameRecordedAction={() => setRefreshKey((key) => key + 1)}
|
||||
onPhaseChangeAction={onPhaseChange}
|
||||
/>
|
||||
<div className="w-full max-w-[520px]">
|
||||
<h2 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">How scoring works</h2>
|
||||
<ul className="mt-1.5 flex flex-col gap-0.5 text-xs leading-relaxed text-muted-foreground/80">
|
||||
<li>
|
||||
Accuracy tracks every keystroke; each wrong character or backspace counts against it. Each message scores accuracy × speed multiplier, up to ~120 points for a fast perfect message.
|
||||
</li>
|
||||
<li>
|
||||
<span className="font-medium text-foreground/80">Sprint:</span> clear exactly 10 messages as fast as possible; maximum score is 1200.
|
||||
</li>
|
||||
<li>
|
||||
<span className="font-medium text-foreground/80">Watch:</span> relay as many messages as possible in 60 seconds; score is unbounded in practice.
|
||||
</li>
|
||||
<li>
|
||||
<span className="font-medium text-foreground/80">XP:</span> earn 0.1 per perfectly-typed message.
|
||||
</li>
|
||||
<li>The lifetime leaderboard ranks Top Score, Top Accuracy, Fastest Sprint, and Most Messages.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<RadioLeaderboard
|
||||
refreshKey={refreshKey}
|
||||
currentUserId={currentUserId}
|
||||
activeOperators={activeOperators}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
265
src/components/frontend/radio/RadioLeaderboard.tsx
Normal file
265
src/components/frontend/radio/RadioLeaderboard.tsx
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Trophy } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { PresenceParticipant } from "@/hooks/useRealtimePresence";
|
||||
|
||||
type LeaderboardTab = "score" | "accuracy" | "messages" | "time";
|
||||
|
||||
interface ApiUser {
|
||||
id: number;
|
||||
username?: string | null;
|
||||
displayName?: string | null;
|
||||
payloadDisplayName?: string | null;
|
||||
}
|
||||
|
||||
interface ApiProfile {
|
||||
id: number;
|
||||
profileTitle?: string | null;
|
||||
user?: ApiUser | number | null;
|
||||
progression?: {
|
||||
minigames?: {
|
||||
radioTraffic?: {
|
||||
totalMessages?: number | null;
|
||||
bestScore?: number | null;
|
||||
bestAccuracy?: number | null;
|
||||
bestSprintTimeMs?: number | null;
|
||||
} | null;
|
||||
} | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
interface LeaderboardRow {
|
||||
id: number;
|
||||
name: string;
|
||||
totalMessages: number;
|
||||
bestScore: number;
|
||||
bestAccuracy: number;
|
||||
bestSprintTimeMs: number;
|
||||
isCurrentUser: boolean;
|
||||
isOutsideTopTen?: boolean;
|
||||
}
|
||||
|
||||
interface TabConfig {
|
||||
readonly label: string;
|
||||
readonly sort: string;
|
||||
readonly matches: (row: LeaderboardRow) => boolean;
|
||||
readonly empty: string;
|
||||
}
|
||||
|
||||
interface RadioLeaderboardProps {
|
||||
refreshKey?: number;
|
||||
currentUserId?: number | string;
|
||||
activeOperators?: PresenceParticipant[];
|
||||
}
|
||||
|
||||
const TAB_ORDER = ["score", "accuracy", "messages", "time"] as const satisfies readonly LeaderboardTab[];
|
||||
const TAB_CONFIG = {
|
||||
score: {
|
||||
label: "Top Score",
|
||||
sort: "-progression.minigames.radioTraffic.bestScore",
|
||||
matches: (row) => row.bestScore > 0,
|
||||
empty: "No scored transmissions yet. Take the first slot!",
|
||||
},
|
||||
accuracy: {
|
||||
label: "Top Accuracy",
|
||||
sort: "-progression.minigames.radioTraffic.bestAccuracy",
|
||||
matches: (row) => row.bestAccuracy > 0,
|
||||
empty: "No accuracy records yet. Relay a perfect transmission!",
|
||||
},
|
||||
messages: {
|
||||
label: "Most Messages",
|
||||
sort: "-progression.minigames.radioTraffic.totalMessages",
|
||||
matches: (row) => row.totalMessages > 0,
|
||||
empty: "No accurate messages yet. Get on frequency!",
|
||||
},
|
||||
time: {
|
||||
label: "Fastest Sprint",
|
||||
sort: "progression.minigames.radioTraffic.bestSprintTimeMs",
|
||||
matches: (row) => row.bestSprintTimeMs > 0,
|
||||
empty: "No sprint times yet. Complete a 10-message sprint!",
|
||||
},
|
||||
} satisfies Record<LeaderboardTab, TabConfig>;
|
||||
|
||||
function rankClass(index: number) {
|
||||
if (index === 0) return "font-bold text-amber-400";
|
||||
if (index === 1) return "font-semibold text-slate-300";
|
||||
if (index === 2) return "font-semibold text-amber-700";
|
||||
return "text-muted-foreground";
|
||||
}
|
||||
|
||||
export function RadioLeaderboard({
|
||||
refreshKey = 0,
|
||||
currentUserId,
|
||||
activeOperators = [],
|
||||
}: RadioLeaderboardProps) {
|
||||
const [tab, setTab] = useState<LeaderboardTab>("score");
|
||||
const [rows, setRows] = useState<LeaderboardRow[] | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const tabConfig = TAB_CONFIG[tab];
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setFailed(false);
|
||||
setRows(null);
|
||||
|
||||
const params = new URLSearchParams({ sort: tabConfig.sort, limit: "100", depth: "1" });
|
||||
fetch(`/api/profiles?${params.toString()}`)
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error("leaderboard fetch failed");
|
||||
return res.json() as Promise<{ docs?: ApiProfile[] }>;
|
||||
})
|
||||
.then((data) => {
|
||||
if (cancelled) return;
|
||||
const mapped: LeaderboardRow[] = (data.docs ?? []).map((doc) => {
|
||||
const radioTraffic = doc.progression?.minigames?.radioTraffic ?? {};
|
||||
const user = typeof doc.user === "object" && doc.user !== null ? doc.user : null;
|
||||
return {
|
||||
id: doc.id,
|
||||
name: user?.displayName || doc.profileTitle || user?.username || `Operator #${doc.id}`,
|
||||
totalMessages: radioTraffic.totalMessages ?? 0,
|
||||
bestScore: radioTraffic.bestScore ?? 0,
|
||||
bestAccuracy: radioTraffic.bestAccuracy ?? 0,
|
||||
bestSprintTimeMs: radioTraffic.bestSprintTimeMs ?? 0,
|
||||
isCurrentUser: user ? String(user.id) === String(currentUserId) : false,
|
||||
};
|
||||
});
|
||||
const visible = mapped.filter(tabConfig.matches).slice(0, 10);
|
||||
const current = mapped.find((row) => row.isCurrentUser);
|
||||
if (current && !visible.some((row) => row.id === current.id)) {
|
||||
visible.push({ ...current, isOutsideTopTen: true });
|
||||
}
|
||||
setRows(visible);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setFailed(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [currentUserId, refreshKey, tabConfig.matches, tabConfig.sort]);
|
||||
|
||||
return (
|
||||
<div className="w-full max-w-[520px] rounded-xl border border-border bg-card">
|
||||
<div className="border-b border-border px-4 py-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Trophy className="size-4 text-amber-400" />
|
||||
<h2 className="text-sm font-semibold">Radio Traffic Leaderboard</h2>
|
||||
<span className="ml-auto text-xs text-muted-foreground">Top 10</span>
|
||||
</div>
|
||||
<div
|
||||
className="mt-3 grid grid-cols-4 gap-1 rounded-lg bg-muted p-1"
|
||||
role="tablist"
|
||||
aria-label="Radio traffic leaderboard"
|
||||
>
|
||||
{TAB_ORDER.map((value) => (
|
||||
<Button
|
||||
key={value}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === value}
|
||||
variant={tab === value ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
className="px-2 text-xs"
|
||||
onClick={() => setTab(value)}
|
||||
>
|
||||
{TAB_CONFIG[value].label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-b border-border px-4 py-2 text-xs text-muted-foreground" aria-live="polite">
|
||||
<span className="font-medium text-emerald-400">
|
||||
{activeOperators.length} {activeOperators.length === 1 ? "operator" : "operators"} on frequency
|
||||
</span>
|
||||
{activeOperators.length > 0 && (
|
||||
<span className="ml-1 text-foreground">
|
||||
({activeOperators.map((operator) => operator.name).join(", ")})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{failed ? (
|
||||
<p className="px-4 py-4 text-sm text-muted-foreground">Could not load the leaderboard.</p>
|
||||
) : rows === null ? (
|
||||
<div className="flex flex-col gap-2 px-4 py-4">
|
||||
<div className="h-4 w-full animate-pulse rounded bg-border" />
|
||||
<div className="h-4 w-3/4 animate-pulse rounded bg-border" />
|
||||
<div className="h-4 w-1/2 animate-pulse rounded bg-border" />
|
||||
</div>
|
||||
) : rows.length === 0 ? (
|
||||
<p className="px-4 py-4 text-sm text-muted-foreground">{tabConfig.empty}</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-left text-xs uppercase tracking-wider text-muted-foreground">
|
||||
<th className="px-4 py-2 font-medium">#</th>
|
||||
<th className="px-2 py-2 font-medium">Operator</th>
|
||||
<th className="px-2 py-2 text-right font-medium">Score</th>
|
||||
<th className="px-2 py-2 text-right font-medium">Accuracy</th>
|
||||
<th className="px-2 py-2 text-right font-medium">Time</th>
|
||||
<th className="px-4 py-2 text-right font-medium">Messages</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-border">
|
||||
{rows.map((row, index) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={cn(
|
||||
row.isCurrentUser && "bg-accent/40",
|
||||
row.isOutsideTopTen && "text-muted-foreground opacity-70",
|
||||
)}
|
||||
title={
|
||||
row.isOutsideTopTen
|
||||
? "Operator status: not currently ranked in the top 10"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<td className="px-4 py-2">
|
||||
<span className={rankClass(index)}>{row.isOutsideTopTen ? "—" : index + 1}</span>
|
||||
</td>
|
||||
<td className="px-2 py-2 font-medium">
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="max-w-[180px] truncate">{row.name}</span>
|
||||
{row.isCurrentUser && (
|
||||
<span className="shrink-0 text-xs text-muted-foreground">(you)</span>
|
||||
)}
|
||||
{row.isOutsideTopTen && (
|
||||
<span className="shrink-0 text-[10px] font-normal uppercase tracking-wide text-muted-foreground">
|
||||
unranked
|
||||
</span>
|
||||
)}
|
||||
{activeOperators.some((operator) => operator.id === row.id) && (
|
||||
<span
|
||||
className="size-2 rounded-full bg-emerald-400"
|
||||
title="Transmitting now"
|
||||
aria-label="Transmitting now"
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-2 py-2 text-right font-semibold tabular-nums">
|
||||
{row.bestScore.toFixed(2)}
|
||||
</td>
|
||||
<td className="px-2 py-2 text-right font-semibold tabular-nums">
|
||||
{(row.bestAccuracy * 100).toFixed(2)}%
|
||||
</td>
|
||||
<td className="px-2 py-2 text-right tabular-nums">
|
||||
{row.bestSprintTimeMs > 0 ? `${(row.bestSprintTimeMs / 1000).toFixed(1)}s` : "—"}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-right tabular-nums text-muted-foreground">
|
||||
{row.totalMessages}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
Reference in a new issue