Polish map & UI into a command-center war-room; rewire live LLM endpoint
Map (WorldMap): - Keep the near-black OpenFreeMap `dark` basemap (verified HTTP 200; the suggested dark-matter / dark-outdoors / liberty-dark variants 404 on that host) so the choropleth nation colors pop - Stable per-nation fills at 0.8 opacity, thin subtle borders, and a brighter thicker amber border for the player nation so "this is me" is always obvious - Hover brightens a region and shows a color-chipped owner + key stats popup; click opens a full dossier popup and focuses the left panel on that nation - Transient, self-cleaning flash (pulsing amber outline) over regions whose ownership changed this turn - Bottom-left legend auto-generated from the region map; per-scenario initial camera (Europe for the WWII scenarios, wider for Cold War / Modern / Aegis) Command-center UI: - New header bar: scenario title, prominent turn + date, the player nation (name + color chip), and a live Idle / "Simulating…" status indicator - 3-column operations-console grid: nation dossier (left) / dominant map (center) / command deck + event feed (right); stacks map-first on mobile - EventFeed: one card per event with a category icon, a colored outcome badge (success/failure/partial/neutral), a nation-colored accent edge, and the turn + date; new events slide in and flash at the top - NationPanel: value-colored animated stat bars (red → green), territory as color-coded region chips, and diplomacy as a list with a colored indicator per relation (ally/rival/war/neutral) - ActionPanel: a "Your move" composer with one prominent Send button and a spinner + "turns can take a few seconds" hint while a turn resolves - sonner error toasts: a 502 / model-down surfaces as "AI temporarily unavailable — try again" Live LLM rewire (server, previously uncommitted): - Default endpoint https://ai.kkhost.pl/v1 (vLLM, no API key); reasoning model qwen3.8-27b; always send a generous max_tokens (4000) so it finishes its chain-of-thought before emitting content; read only `content`, ignore `reasoning`. docker-compose + AGENTS.md updated to match. Tests: the deterministic Playwright e2e gains assertions for the dossier stat bars, the map legend (all nations), and the event-card type icon + outcome badge; it stays fully deterministic under LLM_STUB=1.
This commit is contained in:
+100
-40
@@ -1,10 +1,10 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { CircleDot, Loader2, Radar } from 'lucide-react';
|
||||
import { Toaster } from './components/ui/sonner';
|
||||
import { Button } from './components/ui/button';
|
||||
import { Badge } from './components/ui/badge';
|
||||
import { Separator } from './components/ui/separator';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './components/ui/select';
|
||||
import { cn } from './lib/utils';
|
||||
import PresetPicker from './components/PresetPicker';
|
||||
import NationSelect from './components/NationSelect';
|
||||
import WorldMap from './components/WorldMap';
|
||||
@@ -19,6 +19,19 @@ import type { GameState, Preset, PresetMeta } from '@shared/types';
|
||||
/** Which top-level screen the app is showing. */
|
||||
type Screen = { name: 'home' } | { name: 'pick'; preset: Preset } | { name: 'game' };
|
||||
|
||||
/**
|
||||
* Surface a turn failure. A 502 (live model down / timeout) gets a friendly,
|
||||
* actionable message; anything else passes the underlying error through.
|
||||
*/
|
||||
function toastError(e: unknown): void {
|
||||
const msg = e instanceof Error ? e.message : String(e ?? 'Something went wrong');
|
||||
if (/502|temporarily|timeout|fetch failed|network/i.test(msg)) {
|
||||
toast.error('AI temporarily unavailable — try again');
|
||||
} else {
|
||||
toast.error(msg);
|
||||
}
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [screen, setScreen] = useState<Screen>({ name: 'home' });
|
||||
const [presets, setPresets] = useState<PresetMeta[]>([]);
|
||||
@@ -63,7 +76,7 @@ export default function App() {
|
||||
const { preset } = await api.getPreset(presetId);
|
||||
setScreen({ name: 'pick', preset });
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'Could not load scenario');
|
||||
toastError(e);
|
||||
setScreen({ name: 'home' });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -80,7 +93,7 @@ export default function App() {
|
||||
setAdvisors([]);
|
||||
setScreen({ name: 'game' });
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'Could not start the game');
|
||||
toastError(e);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -96,7 +109,7 @@ export default function App() {
|
||||
const { state } = await api.turn(game.id, action);
|
||||
setGame(state);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'Action failed');
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -112,7 +125,7 @@ export default function App() {
|
||||
const { state } = await api.turn(game.id, undefined, { to, message });
|
||||
setGame(state);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'Diplomacy failed');
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -127,7 +140,7 @@ export default function App() {
|
||||
const { state } = await api.jump(game.id);
|
||||
setGame(state);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'Jump failed');
|
||||
toastError(e);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
@@ -140,7 +153,7 @@ export default function App() {
|
||||
const { suggestions } = await api.advisor(game.id, prompt);
|
||||
setAdvisors(suggestions);
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'Advisor failed');
|
||||
toastError(e);
|
||||
}
|
||||
},
|
||||
[game],
|
||||
@@ -177,12 +190,7 @@ export default function App() {
|
||||
return (
|
||||
<>
|
||||
<Toaster richColors position="top-right" />
|
||||
<NationSelect
|
||||
preset={screen.preset}
|
||||
loading={loading}
|
||||
onPick={pickNation}
|
||||
onBack={goHome}
|
||||
/>
|
||||
<NationSelect preset={screen.preset} loading={loading} onPick={pickNation} onBack={goHome} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -207,7 +215,13 @@ interface GameScreenProps {
|
||||
onHome: () => void;
|
||||
}
|
||||
|
||||
/** The main play view: map + nation dossier on the left, command deck + event feed on the right. */
|
||||
/**
|
||||
* The main play view — an operations console. A top status bar carries the
|
||||
* scenario, the current turn + date, the player nation (color-chipped), and a
|
||||
* live idle/simulating indicator. Below it, a three-column grid: the nation
|
||||
* dossier (left), the dominant map (center), and the command deck + event feed
|
||||
* (right). On small screens these stack map-first.
|
||||
*/
|
||||
function GameScreen({
|
||||
game,
|
||||
regions,
|
||||
@@ -226,38 +240,70 @@ function GameScreen({
|
||||
const nations = Object.values(game.nations).sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex min-h-screen max-w-[1500px] flex-col px-4 py-5 lg:px-6">
|
||||
<header className="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2" data-testid="game-header">
|
||||
<div className="mx-auto flex min-h-screen max-w-[1600px] flex-col px-3 py-4 sm:px-4 lg:px-6">
|
||||
<header
|
||||
data-testid="game-header"
|
||||
className="mb-4 flex flex-wrap items-center gap-x-4 gap-y-3 rounded-xl border bg-card/60 px-4 py-3"
|
||||
>
|
||||
<Button variant="ghost" size="sm" onClick={onHome}>
|
||||
← Scenarios
|
||||
</Button>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<span className="inline-block size-3.5 rounded-full" style={{ background: nationColor(game.playerNationId) }} />
|
||||
<h1 className="text-2xl font-bold tracking-tight">{player?.name ?? game.playerNationId}</h1>
|
||||
<Badge variant="secondary">{game.presetTitle}</Badge>
|
||||
<Radar className="size-5 text-primary" />
|
||||
<div className="leading-tight">
|
||||
<h1 className="text-lg font-bold tracking-tight">History</h1>
|
||||
<p className="text-[11px] text-muted-foreground">{game.presetTitle}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span>
|
||||
Turn <span className="font-semibold tabular-nums text-foreground" data-testid="turn-count">{game.turn}</span>
|
||||
|
||||
<div className="ml-auto flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<div className="text-right leading-none">
|
||||
<div className="text-[10px] font-medium uppercase tracking-widest text-muted-foreground">Turn</div>
|
||||
<div className="mt-1 text-2xl font-bold tabular-nums" data-testid="turn-count">
|
||||
{game.turn}
|
||||
</div>
|
||||
</div>
|
||||
<div className="hidden h-9 w-px bg-border sm:block" />
|
||||
<div className="text-right leading-none">
|
||||
<div className="text-[10px] font-medium uppercase tracking-widest text-muted-foreground">Date</div>
|
||||
<div className="mt-1 text-sm font-semibold tabular-nums" data-testid="game-date">
|
||||
{game.date}
|
||||
</div>
|
||||
</div>
|
||||
<div className="hidden h-9 w-px bg-border sm:block" />
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className="inline-block size-3.5 rounded-full ring-2 ring-white/10"
|
||||
style={{ background: nationColor(game.playerNationId) }}
|
||||
/>
|
||||
<span className="text-sm font-medium" data-testid="player-nation">
|
||||
{player?.name ?? game.playerNationId}
|
||||
</span>
|
||||
</div>
|
||||
<span
|
||||
data-testid="status-indicator"
|
||||
className={cn(
|
||||
'flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium',
|
||||
busy ? 'border-primary/40 bg-primary/10 text-primary' : 'border-border bg-muted/40 text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2 className="size-3 animate-spin" />
|
||||
) : (
|
||||
<CircleDot className="size-3" />
|
||||
)}
|
||||
{busy ? 'Simulating…' : 'Idle'}
|
||||
</span>
|
||||
<Separator orientation="vertical" className="h-4" />
|
||||
<span className="tabular-nums" data-testid="game-date">
|
||||
{game.date}
|
||||
</span>
|
||||
{busy && <span className="animate-pulse text-primary">· simulating…</span>}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="grid flex-1 gap-4 lg:grid-cols-[2fr_1fr]">
|
||||
<section className="min-w-0 space-y-4">
|
||||
<div className="h-[62vh] min-h-[420px] overflow-hidden rounded-xl border">
|
||||
<WorldMap regions={regions} playerNationId={game.playerNationId} className="h-full w-full" />
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-sm font-medium text-muted-foreground">Inspect nation</span>
|
||||
<main className="grid flex-1 gap-4 lg:grid-cols-[300px_minmax(0,1fr)_340px]">
|
||||
{/* Left: nation dossier (mobile order 3). */}
|
||||
<section className="order-3 min-w-0 lg:order-1">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<span className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Inspect</span>
|
||||
<Select value={viewingId} onValueChange={setViewingId}>
|
||||
<SelectTrigger className="w-56" data-testid="inspect-select">
|
||||
<SelectTrigger className="w-full" data-testid="inspect-select">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -269,11 +315,25 @@ function GameScreen({
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<NationPanel nation={viewed} nations={game.nations} isPlayer={viewingId === game.playerNationId} />
|
||||
</section>
|
||||
|
||||
<aside className="flex min-w-0 flex-col gap-4">
|
||||
{/* Center: the dominant map (mobile order 1). */}
|
||||
<section className="order-1 min-w-0 lg:order-2">
|
||||
<div className="relative h-[58vh] min-h-[420px] overflow-hidden rounded-xl border lg:h-[80vh]">
|
||||
<WorldMap
|
||||
regions={regions}
|
||||
playerNationId={game.playerNationId}
|
||||
nations={game.nations}
|
||||
presetId={game.presetId}
|
||||
onFocusNation={setViewingId}
|
||||
className="h-full w-full"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Right: command deck + event feed (mobile order 2). */}
|
||||
<aside className="order-2 flex min-h-0 min-w-0 flex-col gap-4 lg:order-3">
|
||||
<ActionPanel
|
||||
game={game}
|
||||
busy={busy}
|
||||
@@ -283,7 +343,7 @@ function GameScreen({
|
||||
onAdvisor={onAdvisor}
|
||||
onJump={onJump}
|
||||
/>
|
||||
<div className="h-[46vh] min-h-[280px]" data-testid="event-feed-slot">
|
||||
<div className="min-h-[360px] flex-1 lg:min-h-0" data-testid="event-feed-slot">
|
||||
<EventFeed events={game.events} nations={game.nations} />
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { Loader2, Radar, Send } from 'lucide-react';
|
||||
import { Button } from './ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
|
||||
import { Input } from './ui/input';
|
||||
@@ -20,12 +21,12 @@ interface Props {
|
||||
}
|
||||
|
||||
/**
|
||||
* The player's command deck. Three tabs:
|
||||
* - Action: free-text move (the primary way to shape the world).
|
||||
* - Diplomacy: a message to a specific other nation.
|
||||
* - Advisor: ask the LLM for 3–5 in-character action ideas; "Use" feeds one
|
||||
* straight into the Action tab.
|
||||
* A prominent "Jump forward" button auto-simulates the world with no player move.
|
||||
* The player's command deck ("Your move"). Three tabs — Action (free-text move),
|
||||
* Diplomacy (a message to a specific nation), Advisor (ask the LLM for ideas,
|
||||
* "Use" feeds one into the Action tab) — share one prominent Send button that
|
||||
* routes to the active tab. While a turn resolves it shows a spinner + a hint
|
||||
* that turns take a few seconds. A "Jump forward" button auto-simulates the
|
||||
* world with no player move.
|
||||
*/
|
||||
export default function ActionPanel({ game, busy, advisors, onAction, onChat, onAdvisor, onJump }: Props) {
|
||||
const [tab, setTab] = useState('action');
|
||||
@@ -57,10 +58,37 @@ export default function ActionPanel({ game, busy, advisors, onAction, onChat, on
|
||||
setTab('action');
|
||||
};
|
||||
|
||||
// The single Send button routes to the active tab.
|
||||
const sendDisabled =
|
||||
busy ||
|
||||
(tab === 'action'
|
||||
? !action.trim()
|
||||
: tab === 'diplo'
|
||||
? !message.trim() || !target
|
||||
: false);
|
||||
|
||||
const sendLabel = busy
|
||||
? 'Simulating…'
|
||||
: tab === 'action'
|
||||
? 'Take action'
|
||||
: tab === 'diplo'
|
||||
? 'Send message'
|
||||
: 'Ask the advisor';
|
||||
|
||||
const send = () => {
|
||||
if (busy) return;
|
||||
if (tab === 'action') submitAction();
|
||||
else if (tab === 'diplo') submitChat();
|
||||
else onAdvisor(prompt.trim() || undefined);
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="gap-4" data-testid="action-panel">
|
||||
<CardHeader className="flex-row items-center justify-between space-y-0">
|
||||
<CardTitle className="text-base">Command</CardTitle>
|
||||
<div className="flex items-center gap-2">
|
||||
<Radar className="size-4 text-primary" />
|
||||
<CardTitle className="text-base">Your move</CardTitle>
|
||||
</div>
|
||||
<Button variant="secondary" size="sm" onClick={onJump} disabled={busy} data-testid="jump-forward">
|
||||
{busy ? 'Simulating…' : 'Jump forward'}
|
||||
</Button>
|
||||
@@ -88,9 +116,6 @@ export default function ActionPanel({ game, busy, advisors, onAction, onChat, on
|
||||
rows={3}
|
||||
data-testid="action-textarea"
|
||||
/>
|
||||
<Button onClick={submitAction} disabled={busy || !action.trim()} className="w-full" data-testid="action-submit">
|
||||
Take action
|
||||
</Button>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="diplo" className="space-y-2">
|
||||
@@ -113,9 +138,6 @@ export default function ActionPanel({ game, busy, advisors, onAction, onChat, on
|
||||
rows={3}
|
||||
data-testid="chat-message"
|
||||
/>
|
||||
<Button onClick={submitChat} disabled={busy || !message.trim() || !target} className="w-full" data-testid="chat-submit">
|
||||
Send message
|
||||
</Button>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="advisor" className="space-y-2">
|
||||
@@ -125,14 +147,6 @@ export default function ActionPanel({ game, busy, advisors, onAction, onChat, on
|
||||
placeholder="Optional focus — e.g. “the nuclear standoff”"
|
||||
data-testid="advisor-prompt"
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => onAdvisor(prompt.trim() || undefined)}
|
||||
className="w-full"
|
||||
data-testid="advisor-ask"
|
||||
>
|
||||
Ask the advisor
|
||||
</Button>
|
||||
{advisors.length > 0 && (
|
||||
<ul className="space-y-1.5" data-testid="advisor-list">
|
||||
{advisors.map((a, i) => (
|
||||
@@ -151,6 +165,26 @@ export default function ActionPanel({ game, busy, advisors, onAction, onChat, on
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<div className="mt-3 space-y-2">
|
||||
<Button className="h-11 w-full" onClick={send} disabled={sendDisabled} data-testid="action-submit">
|
||||
{busy ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Send className="size-4" />
|
||||
)}
|
||||
{sendLabel}
|
||||
</Button>
|
||||
{busy && (
|
||||
<p
|
||||
className="flex items-center justify-center gap-1.5 text-xs text-muted-foreground"
|
||||
data-testid="sim-hint"
|
||||
>
|
||||
<span className="sim-pulse inline-block size-1.5 rounded-full bg-primary" />
|
||||
The world is thinking — turns can take a few seconds.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,32 @@
|
||||
import {
|
||||
DollarSign,
|
||||
Flame,
|
||||
FlaskConical,
|
||||
Handshake,
|
||||
Landmark,
|
||||
Palette,
|
||||
Radar,
|
||||
Swords,
|
||||
Users,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
import { Badge } from './ui/badge';
|
||||
import { ScrollArea } from './ui/scroll-area';
|
||||
import { EVENT_COLORS, OUTCOME_COLORS } from '@/lib/colors';
|
||||
import type { EventEntry, Nation } from '@shared/types';
|
||||
import { nationColor } from '@shared/protocol';
|
||||
import type { EventEntry, EventType, Nation } from '@shared/types';
|
||||
|
||||
/** One icon per event category, so a type is readable without reading. */
|
||||
const EVENT_ICONS: Record<EventType, LucideIcon> = {
|
||||
military: Swords,
|
||||
diplomatic: Handshake,
|
||||
economic: DollarSign,
|
||||
political: Landmark,
|
||||
social: Users,
|
||||
disaster: Flame,
|
||||
scientific: FlaskConical,
|
||||
cultural: Palette,
|
||||
};
|
||||
|
||||
interface Props {
|
||||
events: EventEntry[];
|
||||
@@ -9,54 +34,80 @@ interface Props {
|
||||
}
|
||||
|
||||
/**
|
||||
* Chronological event log (newest first). Each entry shows the turn it resolved,
|
||||
* its date, a color-coded type, a headline, the narrative, the nation it concerns,
|
||||
* and the outcome. Scrolls internally; the parent supplies a bounded height.
|
||||
* A scrolling event log, newest first. Each event is a card with a category
|
||||
* icon, a color-coded outcome badge, a nation-colored accent edge, and the turn
|
||||
* + date it resolved on. New events slide in and flash briefly at the top.
|
||||
*/
|
||||
export default function EventFeed({ events, nations }: Props) {
|
||||
const latestFirst = [...events].reverse();
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col rounded-xl border bg-card" data-testid="event-feed-panel">
|
||||
<div className="flex items-center justify-between px-4 pt-4">
|
||||
<h2 className="text-sm font-semibold">Event feed</h2>
|
||||
<div
|
||||
className="flex h-full min-h-0 flex-col rounded-xl border bg-card"
|
||||
data-testid="event-feed-panel"
|
||||
>
|
||||
<div className="flex items-center justify-between border-b px-4 py-2.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<Radar className="size-4 text-primary" />
|
||||
<h2 className="text-sm font-semibold tracking-wide">Event feed</h2>
|
||||
</div>
|
||||
<Badge variant="secondary" className="text-xs tabular-nums">
|
||||
{events.length}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="mx-4 mb-4 min-h-0 flex-1">
|
||||
<ScrollArea className="mx-3 mb-3 min-h-0 flex-1">
|
||||
<div className="space-y-2 pr-1" data-testid="event-feed">
|
||||
{latestFirst.length === 0 && (
|
||||
<p className="rounded-md border border-dashed p-3 text-sm text-muted-foreground">
|
||||
<div className="mt-3 rounded-md border border-dashed p-4 text-center text-sm text-muted-foreground">
|
||||
No events yet. Take an action, send a message, or jump forward to move the world.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{latestFirst.map((e) => {
|
||||
const nation = nations[e.nation];
|
||||
const color = EVENT_COLORS[e.type] ?? '#94a3b8';
|
||||
const outcome = OUTCOME_COLORS[e.outcome] ?? '#94a3b8';
|
||||
// Accent edge uses the nation's stable choropleth color (falls back to
|
||||
// the type color if the nation is missing — never crashes).
|
||||
const accent = nation ? nationColor(e.nation) : EVENT_COLORS[e.type] ?? '#94a3b8';
|
||||
const typeColor = EVENT_COLORS[e.type] ?? '#94a3b8';
|
||||
const outcomeColor = OUTCOME_COLORS[e.outcome] ?? '#94a3b8';
|
||||
const Icon = EVENT_ICONS[e.type] ?? Landmark;
|
||||
return (
|
||||
<article key={e.id} className="rounded-lg border bg-card/50 p-2.5" data-testid="event-item">
|
||||
<div className="mb-1 flex items-center gap-1.5 text-[11px] text-muted-foreground">
|
||||
<span className="font-medium tabular-nums">T{e.turn}</span>
|
||||
<article
|
||||
key={e.id}
|
||||
className="event-new relative overflow-hidden rounded-lg border bg-card/50 p-3 pl-4"
|
||||
style={{ borderLeft: `3px solid ${accent}` }}
|
||||
data-testid="event-item"
|
||||
>
|
||||
<div className="mb-1.5 flex items-center gap-1.5 text-[11px] text-muted-foreground">
|
||||
<span className="font-semibold tabular-nums text-foreground/70">T{e.turn}</span>
|
||||
<span>·</span>
|
||||
<span className="tabular-nums">{e.date}</span>
|
||||
<span className="ml-auto inline-flex items-center gap-1.5">
|
||||
<span className="inline-block size-2 rounded-full" style={{ background: color }} />
|
||||
{e.type}
|
||||
<span
|
||||
className="ml-auto inline-flex items-center gap-1.5 rounded-full px-1.5 py-0.5"
|
||||
style={{ color: typeColor, background: `${typeColor}1a` }}
|
||||
>
|
||||
<Icon className="size-3" data-testid="event-type-icon" aria-hidden />
|
||||
<span data-testid="event-type" className="capitalize">
|
||||
{e.type}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm font-medium leading-snug" style={{ color }}>
|
||||
{e.title}
|
||||
</p>
|
||||
<p className="mt-0.5 text-sm leading-snug text-foreground/80">{e.text}</p>
|
||||
<div className="mt-1.5 flex items-center gap-2 text-[11px] text-muted-foreground">
|
||||
<span>{nation?.name ?? e.nation}</span>
|
||||
<p className="text-sm font-medium leading-snug">{e.title}</p>
|
||||
<p className="mt-1 text-[13px] leading-snug text-foreground/75">{e.text}</p>
|
||||
<div className="mt-2 flex items-center gap-2 text-[11px]">
|
||||
<span className="inline-flex min-w-0 items-center gap-1.5">
|
||||
<span className="inline-block size-2 shrink-0 rounded-full" style={{ background: accent }} />
|
||||
<span className="truncate text-muted-foreground">{nation?.name ?? e.nation}</span>
|
||||
</span>
|
||||
<span
|
||||
className="ml-auto rounded px-1.5 py-0.5 font-medium capitalize"
|
||||
style={{ background: `${outcome}22`, color: outcome }}
|
||||
className="ml-auto shrink-0 rounded-md px-2 py-0.5 font-semibold capitalize"
|
||||
style={{
|
||||
background: `${outcomeColor}22`,
|
||||
color: outcomeColor,
|
||||
border: `1px solid ${outcomeColor}55`,
|
||||
}}
|
||||
data-testid="event-outcome"
|
||||
>
|
||||
{e.outcome}
|
||||
</span>
|
||||
|
||||
@@ -3,7 +3,16 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './ui/
|
||||
import StatBar from './StatBar';
|
||||
import { nationColor } from '@shared/protocol';
|
||||
import { RELATION_COLORS } from '@/lib/colors';
|
||||
import type { Nation } from '@shared/types';
|
||||
import type { Nation, RelationStatus } from '@shared/types';
|
||||
|
||||
/** Human labels for a diplomatic status (the raw value is kept in data-attrs). */
|
||||
const RELATION_LABEL: Record<RelationStatus, string> = {
|
||||
ally: 'Ally',
|
||||
neutral: 'Neutral',
|
||||
rival: 'Rival',
|
||||
hostile: 'Hostile',
|
||||
war: 'At war',
|
||||
};
|
||||
|
||||
interface Props {
|
||||
nation: Nation;
|
||||
@@ -13,10 +22,11 @@ interface Props {
|
||||
}
|
||||
|
||||
/**
|
||||
* A single nation's dossier: identity, the four 0–100 stat bars (colored by the
|
||||
* nation's stable choropleth color), territory count, and its diplomatic posture
|
||||
* toward every other nation. Used for the player (highlighted) or any inspected
|
||||
* nation.
|
||||
* A single nation's dossier: identity + color chip, the four 0–100 stat bars
|
||||
* (colored by value: low = red → high = green, animated on change), territory as
|
||||
* color-coded region chips, and diplomacy as a list with a colored indicator per
|
||||
* relation (ally = green, rival = amber, war = red, neutral = slate). Used for
|
||||
* the player (highlighted) or any inspected nation.
|
||||
*/
|
||||
export default function NationPanel({ nation, nations, isPlayer }: Props) {
|
||||
const color = nationColor(nation.id);
|
||||
@@ -24,67 +34,109 @@ export default function NationPanel({ nation, nations, isPlayer }: Props) {
|
||||
const regions = nation.territory;
|
||||
|
||||
return (
|
||||
<Card data-testid="nation-panel" className={isPlayer ? 'gap-4 border-primary/40' : 'gap-4'}>
|
||||
<CardHeader className="flex-row items-center justify-between space-y-0">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<span className="inline-block size-3.5 rounded-full" style={{ background: color }} />
|
||||
<div className="space-y-0.5">
|
||||
<CardTitle className="text-lg">{nation.name}</CardTitle>
|
||||
<Card data-testid="nation-panel" className={isPlayer ? 'border-primary/40' : undefined}>
|
||||
<CardHeader className="space-y-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<span
|
||||
className="inline-block size-4 shrink-0 rounded-md ring-2 ring-white/10"
|
||||
style={{ background: color }}
|
||||
data-testid="nation-color-chip"
|
||||
/>
|
||||
<div className="min-w-0 flex-1 space-y-0.5">
|
||||
<CardTitle className="truncate text-lg">{nation.name}</CardTitle>
|
||||
<CardDescription>
|
||||
{nation.type} · {regions.length} region{regions.length === 1 ? '' : 's'}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{isPlayer && (
|
||||
<Badge variant="default" className="shrink-0">
|
||||
Your nation
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Badge variant={isPlayer ? 'default' : 'secondary'} className="shrink-0">
|
||||
{isPlayer ? 'Your nation' : 'Other'}
|
||||
</Badge>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-x-6 gap-y-2 sm:grid-cols-2">
|
||||
<StatBar label="Military" value={nation.stats.military} color={color} testId={isPlayer ? 'stat-military' : undefined} />
|
||||
<StatBar label="Economy" value={nation.stats.economy} color={color} testId={isPlayer ? 'stat-economy' : undefined} />
|
||||
<StatBar label="Stability" value={nation.stats.stability} color={color} testId={isPlayer ? 'stat-stability' : undefined} />
|
||||
<StatBar label="Population" value={nation.stats.population} color={color} testId={isPlayer ? 'stat-population' : undefined} />
|
||||
</div>
|
||||
<CardContent className="space-y-5">
|
||||
<section>
|
||||
<h3 className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Status
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
<StatBar
|
||||
label="Military"
|
||||
value={nation.stats.military}
|
||||
testId={isPlayer ? 'stat-military' : undefined}
|
||||
/>
|
||||
<StatBar
|
||||
label="Economy"
|
||||
value={nation.stats.economy}
|
||||
testId={isPlayer ? 'stat-economy' : undefined}
|
||||
/>
|
||||
<StatBar
|
||||
label="Stability"
|
||||
value={nation.stats.stability}
|
||||
testId={isPlayer ? 'stat-stability' : undefined}
|
||||
/>
|
||||
<StatBar
|
||||
label="Population"
|
||||
value={nation.stats.population}
|
||||
testId={isPlayer ? 'stat-population' : undefined}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{regions.length > 0 && (
|
||||
<div>
|
||||
<h3 className="mb-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">Territory</h3>
|
||||
<section>
|
||||
<h3 className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Territory
|
||||
</h3>
|
||||
{regions.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{regions.map((code) => (
|
||||
<span
|
||||
key={code}
|
||||
className="rounded border px-1.5 py-0.5 text-xs tabular-nums"
|
||||
style={{ borderColor: `${color}66`, color }}
|
||||
style={{ borderColor: `${color}66`, color, background: `${color}12` }}
|
||||
>
|
||||
{code}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">No territory.</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{relations.length > 0 && (
|
||||
<div>
|
||||
<h3 className="mb-1.5 text-xs font-medium uppercase tracking-wide text-muted-foreground">Diplomacy</h3>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<section>
|
||||
<h3 className="mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Diplomacy
|
||||
</h3>
|
||||
{relations.length > 0 ? (
|
||||
<ul className="space-y-1.5" data-testid="relations-list">
|
||||
{relations.map(([id, status]) => {
|
||||
const other = nations[id];
|
||||
const c = RELATION_COLORS[status] ?? '#94a3b8';
|
||||
return (
|
||||
<span
|
||||
<li
|
||||
key={id}
|
||||
className="rounded-md border px-2 py-0.5 text-xs"
|
||||
style={{ borderColor: `${c}66`, color: c }}
|
||||
className="flex items-center gap-2 text-sm"
|
||||
data-testid="relation-row"
|
||||
data-status={status}
|
||||
>
|
||||
{other?.name ?? id}: {status}
|
||||
</span>
|
||||
<span className="inline-block size-2.5 shrink-0 rounded-full" style={{ background: c }} />
|
||||
<span className="min-w-0 flex-1 truncate text-foreground/85">
|
||||
{other?.name ?? id}
|
||||
</span>
|
||||
<span className="shrink-0 text-xs font-medium" style={{ color: c }}>
|
||||
{RELATION_LABEL[status] ?? status}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">No diplomatic relations yet.</p>
|
||||
)}
|
||||
</section>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -1,26 +1,35 @@
|
||||
import { cn } from '@/lib/utils';
|
||||
import { statValueColor } from '@/lib/colors';
|
||||
|
||||
interface Props {
|
||||
label: string;
|
||||
value: number;
|
||||
/**
|
||||
* Optional explicit bar color. When omitted, the bar is colored by its value
|
||||
* on a red → yellow → green ramp (low = danger, high = strong).
|
||||
*/
|
||||
color?: string;
|
||||
testId?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** A compact 0-100 stat bar with a value readout. */
|
||||
/**
|
||||
* A compact 0–100 stat bar. The fill animates (width + color) when the value
|
||||
* changes, so a stat bump is visible at a glance. Defaults to a value-driven
|
||||
* red→green color so a low stat reads as "danger".
|
||||
*/
|
||||
export default function StatBar({ label, value, color, testId, className }: Props) {
|
||||
const v = Math.max(0, Math.min(100, Math.round(value)));
|
||||
return (
|
||||
<div className={cn('flex items-center gap-2 text-xs', className)}>
|
||||
<span className="w-12 shrink-0 capitalize text-muted-foreground">{label}</span>
|
||||
<span className="w-16 shrink-0 capitalize text-muted-foreground">{label}</span>
|
||||
<div className="h-2 flex-1 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
className="h-full rounded-full transition-all"
|
||||
style={{ width: `${v}%`, background: color ?? 'var(--primary)' }}
|
||||
className="h-full rounded-full transition-[width,background-color] duration-500 ease-out"
|
||||
style={{ width: `${v}%`, background: color ?? statValueColor(v) }}
|
||||
/>
|
||||
</div>
|
||||
<span className="w-7 text-right tabular-nums" data-testid={testId}>
|
||||
<span className="w-8 shrink-0 text-right font-semibold tabular-nums" data-testid={testId}>
|
||||
{v}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
+305
-39
@@ -1,7 +1,9 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import * as maplibregl from 'maplibre-gl';
|
||||
import 'maplibre-gl/dist/maplibre-gl.css';
|
||||
import type { RegionMap } from '@shared/protocol';
|
||||
import type { RegionMap, RegionOwner } from '@shared/protocol';
|
||||
import type { Nation } from '@shared/types';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// Minimal GeoJSON types (avoids a hard @types/geojson dependency).
|
||||
interface GeoFeature {
|
||||
@@ -14,18 +16,47 @@ interface FeatureCollection {
|
||||
type: 'FeatureCollection';
|
||||
features: GeoFeature[];
|
||||
}
|
||||
type GeoSource = maplibregl.GeoJSONSource;
|
||||
|
||||
// Remote OpenFreeMap dark basemap ("command center" look).
|
||||
// Remote OpenFreeMap "dark" basemap — a near-black (rgb 12,12,12) canvas so the
|
||||
// choropleth nation colors pop. (Verified HTTP 200; the suggested dark-matter /
|
||||
// dark-outdoors / liberty-dark variants do not exist on that host.)
|
||||
const STYLE_URL = 'https://tiles.openfreemap.org/styles/dark';
|
||||
|
||||
const COUNTRIES_SOURCE = 'countries';
|
||||
const HOVER_SOURCE = 'hover';
|
||||
const FLASH_SOURCE = 'flash';
|
||||
const FILL_LAYER = 'countries-fill';
|
||||
const LINE_LAYER = 'countries-line';
|
||||
const PLAYER_LINE = 'player-line';
|
||||
const FLASH_LINE = 'flash-line';
|
||||
const HOVER_FILL = 'hover-fill';
|
||||
const HOVER_LINE = 'hover-line';
|
||||
|
||||
function applyRegions(
|
||||
geo: FeatureCollection,
|
||||
regions: RegionMap,
|
||||
playerNationId: string,
|
||||
): FeatureCollection {
|
||||
/** Sensible per-scenario initial camera: Europe for the WWII scenarios, wider for the global ones. */
|
||||
function cameraForPreset(presetId: string): { center: [number, number]; zoom: number } {
|
||||
switch (presetId) {
|
||||
case 'wwii-1939':
|
||||
case 'no-wwii-1940':
|
||||
return { center: [12, 48], zoom: 3.4 }; // Europe
|
||||
case 'coldwar-1955':
|
||||
return { center: [-18, 42], zoom: 2.4 }; // Atlantic: both superpowers
|
||||
case 'modern-2025':
|
||||
return { center: [10, 25], zoom: 1.7 }; // The whole world
|
||||
case 'aegis-2400':
|
||||
return { center: [10, 25], zoom: 1.6 }; // Far-future, global view
|
||||
default:
|
||||
return { center: [10, 25], zoom: 1.8 };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stamp the current ownership + colors onto a clone of the base geo. Each region
|
||||
* carries its owner's stable fill color, a subtle stroke, and a flag for the
|
||||
* player's own regions (rendered as a brighter, thicker border by a dedicated
|
||||
* layer). Unknown owners fall back to a faint neutral fill — never an error.
|
||||
*/
|
||||
function applyRegions(geo: FeatureCollection, regions: RegionMap, playerNationId: string): FeatureCollection {
|
||||
const out: FeatureCollection = JSON.parse(JSON.stringify(geo));
|
||||
for (const f of out.features) {
|
||||
f.properties = f.properties ?? {};
|
||||
@@ -33,12 +64,11 @@ function applyRegions(
|
||||
if (r) {
|
||||
f.properties.fill = r.color;
|
||||
f.properties.owner = r.owner;
|
||||
// Highlight the player's regions with a bright stroke.
|
||||
f.properties.stroke = r.ownerId === playerNationId ? '#fbbf24' : 'rgba(255,255,255,0.18)';
|
||||
f.properties.stroke = 'rgba(255,255,255,0.10)';
|
||||
f.properties.isPlayer = r.ownerId === playerNationId ? 1 : 0;
|
||||
} else {
|
||||
f.properties.fill = 'rgba(148,163,184,0.06)';
|
||||
f.properties.stroke = 'rgba(255,255,255,0.08)';
|
||||
f.properties.fill = 'rgba(148,163,184,0.05)';
|
||||
f.properties.stroke = 'rgba(255,255,255,0.06)';
|
||||
f.properties.owner = '';
|
||||
f.properties.isPlayer = 0;
|
||||
}
|
||||
@@ -46,42 +76,144 @@ function applyRegions(
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Build a FeatureCollection of just the features whose id is in `codes` (cloned). */
|
||||
function featuresByCodes(geo: FeatureCollection, codes: Iterable<string>): FeatureCollection {
|
||||
const set = new Set(codes);
|
||||
const features = geo.features.filter((f) => f.id != null && set.has(String(f.id)));
|
||||
return { type: 'FeatureCollection', features: JSON.parse(JSON.stringify(features)) };
|
||||
}
|
||||
|
||||
const esc = (s: string) =>
|
||||
s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] as string));
|
||||
|
||||
function statRow(label: string, value?: number): string {
|
||||
if (value == null || Number.isNaN(value)) return '';
|
||||
return `<div class="hm-stat"><span class="hm-stat-k">${label}</span><span class="hm-stat-v">${Math.round(value)}</span></div>`;
|
||||
}
|
||||
|
||||
/** Compact hover tooltip: country, its owner (color-chipped), and 1–2 key stats. */
|
||||
function hoverHtml(countryName: string, region?: RegionOwner, nation?: Nation): string {
|
||||
if (!region || !nation) {
|
||||
return `<div class="hm-popup"><div class="hm-popup-title">${esc(countryName || 'Unclaimed')}</div><div class="hm-popup-sub">No owner</div></div>`;
|
||||
}
|
||||
const stats = [statRow('Mil', nation.stats.military), statRow('Eco', nation.stats.economy)].join('');
|
||||
return `<div class="hm-popup">
|
||||
<div class="hm-popup-title">${esc(countryName || region.owner)}</div>
|
||||
<div class="hm-popup-owner"><span class="hm-chip" style="background:${region.color}"></span>${esc(region.owner)}</div>
|
||||
<div class="hm-stats">${stats}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** Click popup: the full owning-nation profile with all four stats. */
|
||||
function clickHtml(countryName: string, region?: RegionOwner, nation?: Nation): string {
|
||||
if (!region || !nation) {
|
||||
return `<div class="hm-popup"><div class="hm-popup-title">${esc(countryName || 'Unclaimed')}</div><div class="hm-popup-sub">No owner</div></div>`;
|
||||
}
|
||||
const stats = [
|
||||
statRow('Mil', nation.stats.military),
|
||||
statRow('Eco', nation.stats.economy),
|
||||
statRow('Stab', nation.stats.stability),
|
||||
statRow('Pop', nation.stats.population),
|
||||
].join('');
|
||||
const regions = nation.territory.length;
|
||||
return `<div class="hm-popup">
|
||||
<div class="hm-popup-title">${esc(countryName || region.owner)}</div>
|
||||
<div class="hm-popup-owner hm-popup-owner-big"><span class="hm-chip" style="background:${region.color}"></span>${esc(region.owner)}</div>
|
||||
<div class="hm-popup-sub">${regions} region${regions === 1 ? '' : 's'} · click focuses the dossier</div>
|
||||
<div class="hm-stats">${stats}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** Small bottom-left legend mapping each nation on the map to its stable color. */
|
||||
function MapLegend({ regions }: { regions: RegionMap }) {
|
||||
const owners = new Map<string, { color: string; owner: string }>();
|
||||
for (const r of Object.values(regions)) {
|
||||
if (r.ownerId && !owners.has(r.ownerId)) owners.set(r.ownerId, { color: r.color, owner: r.owner });
|
||||
}
|
||||
const list = [...owners.entries()].sort((a, b) => a[1].owner.localeCompare(b[1].owner));
|
||||
if (list.length === 0) return null;
|
||||
return (
|
||||
<div
|
||||
data-testid="map-legend"
|
||||
className="pointer-events-none absolute bottom-3 left-3 z-10 max-h-[62%] overflow-hidden rounded-lg border bg-card/85 p-2.5 backdrop-blur-sm"
|
||||
>
|
||||
<div className="mb-1.5 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground">
|
||||
Nations
|
||||
</div>
|
||||
<ul className="space-y-1">
|
||||
{list.map(([id, o]) => (
|
||||
<li key={id} data-testid="map-legend-item" className="flex items-center gap-1.5 text-xs">
|
||||
<span className="inline-block size-2.5 shrink-0 rounded-sm" style={{ background: o.color }} />
|
||||
<span className="truncate">{o.owner}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface Props {
|
||||
regions: RegionMap;
|
||||
playerNationId: string;
|
||||
/** All nations, for hover/click stats and color chips. */
|
||||
nations: Record<string, Nation>;
|
||||
/** The active scenario id, for a sensible initial camera. */
|
||||
presetId: string;
|
||||
className?: string;
|
||||
/** Called when a region is clicked, so the dossier can focus its owner. */
|
||||
onFocusNation?: (id: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* World basemap (MapLibre GL) + a country choropleth colored by the owning
|
||||
* nation. Ported from flight's Map.tsx (remote style + idempotent `ensureLayers`
|
||||
* re-establish on `styledata`), stripped of all flight-specific data/logic.
|
||||
* nation. The choropleth is the star: a near-black basemap, per-nation stable
|
||||
* fills, subtle borders, a brighter/thicker border for the player, hover + click
|
||||
* popups with owner + stats, a transient flash on territory changes, a
|
||||
* bottom-left legend, and a per-scenario initial camera.
|
||||
*/
|
||||
export default function WorldMap({ regions, playerNationId, className }: Props) {
|
||||
export default function WorldMap({ regions, playerNationId, nations, presetId, className, onFocusNation }: Props) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const mapRef = useRef<maplibregl.Map | null>(null);
|
||||
const baseGeoRef = useRef<FeatureCollection | null>(null);
|
||||
// Latest props, so the mount effect's (re)establish closure always sees them.
|
||||
const regionsRef = useRef(regions);
|
||||
const nationsRef = useRef(nations);
|
||||
const playerRef = useRef(playerNationId);
|
||||
const presetRef = useRef(presetId);
|
||||
const onFocusNationRef = useRef(onFocusNation);
|
||||
regionsRef.current = regions;
|
||||
nationsRef.current = nations;
|
||||
playerRef.current = playerNationId;
|
||||
presetRef.current = presetId;
|
||||
onFocusNationRef.current = onFocusNation;
|
||||
|
||||
// Diffing state for the transient territory-change flash (owned by this component
|
||||
// so a resync with identical data never re-flashes).
|
||||
const prevRegionsRef = useRef<RegionMap | null>(null);
|
||||
const primedRef = useRef(false);
|
||||
const flashApiRef = useRef<((codes: string[]) => void) | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return;
|
||||
let cancelled = false;
|
||||
let flashRaf = 0;
|
||||
|
||||
const cam = cameraForPreset(presetRef.current);
|
||||
const map = new maplibregl.Map({
|
||||
container: containerRef.current,
|
||||
style: STYLE_URL,
|
||||
center: [15, 50],
|
||||
zoom: 2.5,
|
||||
center: cam.center,
|
||||
zoom: cam.zoom,
|
||||
minZoom: 1.25,
|
||||
maxZoom: 8,
|
||||
attributionControl: { compact: true },
|
||||
});
|
||||
mapRef.current = map;
|
||||
|
||||
const hoverPopup = new maplibregl.Popup({ closeButton: false, closeOnClick: false, offset: 10 });
|
||||
const clickPopup = new maplibregl.Popup({ closeButton: true, closeOnClick: true, offset: 12 });
|
||||
let lastHoverId: string | null = null;
|
||||
|
||||
const loadGeo = (): Promise<FeatureCollection> =>
|
||||
baseGeoRef.current
|
||||
? Promise.resolve(baseGeoRef.current)
|
||||
@@ -95,19 +227,89 @@ export default function WorldMap({ regions, playerNationId, className }: Props)
|
||||
return g;
|
||||
});
|
||||
|
||||
const onCountryClick = (e: maplibregl.MapLayerMouseEvent) => {
|
||||
const emptyFC = (): FeatureCollection => ({ type: 'FeatureCollection', features: [] });
|
||||
|
||||
// Transient flash: pulse a bright outline over the changed regions, then fade
|
||||
// to zero over a few seconds and self-clean. Idempotent per call.
|
||||
function animateFlash(codes: string[]) {
|
||||
const geo = baseGeoRef.current;
|
||||
const src = map.getSource(FLASH_SOURCE) as GeoSource | undefined;
|
||||
if (!geo || !src || cancelled) return;
|
||||
src.setData(featuresByCodes(geo, codes));
|
||||
if (!map.getLayer(FLASH_LINE)) {
|
||||
// Defensive re-add (normally created by ensureLayers). Keep it beneath the
|
||||
// hover highlight when that layer exists; otherwise just append.
|
||||
map.addLayer(
|
||||
{
|
||||
id: FLASH_LINE,
|
||||
type: 'line',
|
||||
source: FLASH_SOURCE,
|
||||
paint: { 'line-color': '#fbbf24', 'line-width': 2.6, 'line-opacity': 0 },
|
||||
},
|
||||
map.getLayer(HOVER_FILL) ? HOVER_FILL : undefined,
|
||||
);
|
||||
}
|
||||
cancelAnimationFrame(flashRaf);
|
||||
const start = performance.now();
|
||||
const DURATION = 2600;
|
||||
const tick = (now: number) => {
|
||||
if (cancelled) return;
|
||||
const t = Math.min(1, (now - start) / DURATION);
|
||||
const pulse = 0.55 + 0.45 * Math.sin(t * Math.PI * 3);
|
||||
const opacity = t >= 1 ? 0 : 0.95 * (1 - t) * pulse;
|
||||
try {
|
||||
map.setPaintProperty(FLASH_LINE, 'line-opacity', opacity);
|
||||
} catch {
|
||||
/* map removed mid-animation */
|
||||
}
|
||||
if (t < 1) flashRaf = requestAnimationFrame(tick);
|
||||
};
|
||||
flashRaf = requestAnimationFrame(tick);
|
||||
}
|
||||
flashApiRef.current = animateFlash;
|
||||
|
||||
const onHover = (e: maplibregl.MapLayerMouseEvent) => {
|
||||
const f = e.features?.[0];
|
||||
if (!f) return;
|
||||
const p = f.properties as { owner?: string; name?: string; isPlayer?: number };
|
||||
const label = p.owner ? `${p.owner}${p.isPlayer ? ' (your nation)' : ''}` : p.name ?? 'Unclaimed';
|
||||
new maplibregl.Popup({ offset: 8 })
|
||||
.setLngLat(f.geometry.coordinates as [number, number])
|
||||
.setText(label)
|
||||
const id = f.id == null ? null : String(f.id);
|
||||
if (id && id !== lastHoverId) {
|
||||
lastHoverId = id;
|
||||
const geo = baseGeoRef.current;
|
||||
const feat = geo?.features.find((x) => x.id != null && String(x.id) === id);
|
||||
(map.getSource(HOVER_SOURCE) as GeoSource | undefined)?.setData(
|
||||
feat ? { type: 'FeatureCollection', features: [JSON.parse(JSON.stringify(feat))] } : emptyFC(),
|
||||
);
|
||||
}
|
||||
const p = f.properties as { name?: string };
|
||||
const region = id ? regionsRef.current[id] : undefined;
|
||||
const nation = region ? nationsRef.current[region.ownerId] : undefined;
|
||||
hoverPopup
|
||||
.setLngLat(e.lngLat)
|
||||
.setHTML(hoverHtml(p?.name ?? id ?? '', region, nation))
|
||||
.addTo(map);
|
||||
map.getCanvas().style.cursor = 'pointer';
|
||||
};
|
||||
|
||||
// Idempotent: re-adds the countries source + layers after any setStyle, and on
|
||||
// first load. (Vite serves MapLibre's worker automatically, so no setWorkerUrl.)
|
||||
const onHoverOut = () => {
|
||||
lastHoverId = null;
|
||||
(map.getSource(HOVER_SOURCE) as GeoSource | undefined)?.setData(emptyFC());
|
||||
hoverPopup.remove();
|
||||
map.getCanvas().style.cursor = '';
|
||||
};
|
||||
|
||||
const onClick = (e: maplibregl.MapLayerMouseEvent) => {
|
||||
const f = e.features?.[0];
|
||||
if (!f) return;
|
||||
const id = f.id == null ? null : String(f.id);
|
||||
const p = f.properties as { name?: string };
|
||||
const region = id ? regionsRef.current[id] : undefined;
|
||||
const nation = region ? nationsRef.current[region.ownerId] : undefined;
|
||||
clickPopup.setLngLat(e.lngLat).setHTML(clickHtml(p?.name ?? id ?? '', region, nation)).addTo(map);
|
||||
if (region?.ownerId) onFocusNationRef.current?.(region.ownerId);
|
||||
};
|
||||
|
||||
// Idempotent: (re)adds the sources + layers after any setStyle and on first
|
||||
// load. (Vite serves MapLibre's worker automatically, so no setWorkerUrl.)
|
||||
const ensureLayers = async () => {
|
||||
let geo: FeatureCollection;
|
||||
try {
|
||||
@@ -123,15 +325,18 @@ export default function WorldMap({ regions, playerNationId, className }: Props)
|
||||
data: applyRegions(geo, regionsRef.current, playerRef.current),
|
||||
});
|
||||
}
|
||||
if (!map.getSource(HOVER_SOURCE)) {
|
||||
map.addSource(HOVER_SOURCE, { type: 'geojson', data: emptyFC() });
|
||||
}
|
||||
if (!map.getSource(FLASH_SOURCE)) {
|
||||
map.addSource(FLASH_SOURCE, { type: 'geojson', data: emptyFC() });
|
||||
}
|
||||
if (!map.getLayer(FILL_LAYER)) {
|
||||
map.addLayer({
|
||||
id: FILL_LAYER,
|
||||
type: 'fill',
|
||||
source: COUNTRIES_SOURCE,
|
||||
paint: {
|
||||
'fill-color': ['get', 'fill'],
|
||||
'fill-opacity': 0.55,
|
||||
},
|
||||
paint: { 'fill-color': ['get', 'fill'], 'fill-opacity': 0.8 },
|
||||
});
|
||||
}
|
||||
if (!map.getLayer(LINE_LAYER)) {
|
||||
@@ -139,14 +344,52 @@ export default function WorldMap({ regions, playerNationId, className }: Props)
|
||||
id: LINE_LAYER,
|
||||
type: 'line',
|
||||
source: COUNTRIES_SOURCE,
|
||||
paint: {
|
||||
'line-color': ['get', 'stroke'],
|
||||
'line-width': 0.75,
|
||||
},
|
||||
paint: { 'line-color': ['get', 'stroke'], 'line-width': 0.6, 'line-opacity': 0.9 },
|
||||
});
|
||||
}
|
||||
map.off('click', FILL_LAYER, onCountryClick);
|
||||
map.on('click', FILL_LAYER, onCountryClick);
|
||||
// NOTE: layers are added in bottom→top order (each appends on top). The
|
||||
// stack is: fill, base borders, player border, territory-change flash,
|
||||
// hover brighten, hover outline. Do not use a `beforeId` here — it throws
|
||||
// if that layer does not exist yet on a fresh style load.
|
||||
if (!map.getLayer(PLAYER_LINE)) {
|
||||
map.addLayer({
|
||||
id: PLAYER_LINE,
|
||||
type: 'line',
|
||||
source: COUNTRIES_SOURCE,
|
||||
filter: ['==', ['get', 'isPlayer'], 1],
|
||||
paint: { 'line-color': '#f59e0b', 'line-width': 2.2, 'line-opacity': 0.95 },
|
||||
});
|
||||
}
|
||||
if (!map.getLayer(FLASH_LINE)) {
|
||||
map.addLayer({
|
||||
id: FLASH_LINE,
|
||||
type: 'line',
|
||||
source: FLASH_SOURCE,
|
||||
paint: { 'line-color': '#fbbf24', 'line-width': 2.6, 'line-opacity': 0 },
|
||||
});
|
||||
}
|
||||
if (!map.getLayer(HOVER_FILL)) {
|
||||
map.addLayer({
|
||||
id: HOVER_FILL,
|
||||
type: 'fill',
|
||||
source: HOVER_SOURCE,
|
||||
paint: { 'fill-color': '#ffffff', 'fill-opacity': 0.16 },
|
||||
});
|
||||
}
|
||||
if (!map.getLayer(HOVER_LINE)) {
|
||||
map.addLayer({
|
||||
id: HOVER_LINE,
|
||||
type: 'line',
|
||||
source: HOVER_SOURCE,
|
||||
paint: { 'line-color': '#ffffff', 'line-width': 1.6, 'line-opacity': 0.9 },
|
||||
});
|
||||
}
|
||||
map.off('mousemove', FILL_LAYER, onHover);
|
||||
map.off('mouseout', FILL_LAYER, onHoverOut);
|
||||
map.off('click', FILL_LAYER, onClick);
|
||||
map.on('mousemove', FILL_LAYER, onHover);
|
||||
map.on('mouseout', FILL_LAYER, onHoverOut);
|
||||
map.on('click', FILL_LAYER, onClick);
|
||||
};
|
||||
|
||||
if (map.isStyleLoaded()) void ensureLayers();
|
||||
@@ -154,19 +397,42 @@ export default function WorldMap({ regions, playerNationId, className }: Props)
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
cancelAnimationFrame(flashRaf);
|
||||
flashApiRef.current = null;
|
||||
map.remove();
|
||||
mapRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Re-color the choropleth whenever the region ownership changes (each turn).
|
||||
// Re-color the choropleth whenever ownership changes, and flash any regions
|
||||
// whose owner changed since the last update (transient, self-cleaning).
|
||||
useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
const geo = baseGeoRef.current;
|
||||
if (!map || !geo) return;
|
||||
const src = map.getSource(COUNTRIES_SOURCE) as maplibregl.GeoJSONSource | undefined;
|
||||
if (src) void src.setData(applyRegions(geo, regions, playerNationId));
|
||||
const cur = regions;
|
||||
const prev = prevRegionsRef.current;
|
||||
prevRegionsRef.current = cur;
|
||||
const wasPrimed = primedRef.current;
|
||||
if (Object.keys(cur).length > 0) primedRef.current = true;
|
||||
|
||||
if (map && geo) {
|
||||
const src = map.getSource(COUNTRIES_SOURCE) as GeoSource | undefined;
|
||||
if (src) void src.setData(applyRegions(geo, cur, playerNationId));
|
||||
}
|
||||
|
||||
if (wasPrimed && prev) {
|
||||
const changed = new Set<string>();
|
||||
for (const code of new Set([...Object.keys(prev), ...Object.keys(cur)])) {
|
||||
if ((prev[code]?.ownerId ?? '') !== (cur[code]?.ownerId ?? '')) changed.add(code);
|
||||
}
|
||||
if (changed.size > 0) flashApiRef.current?.([...changed]);
|
||||
}
|
||||
}, [regions, playerNationId]);
|
||||
|
||||
return <div ref={containerRef} data-testid="world-map" className={className} />;
|
||||
return (
|
||||
<div className={cn('relative h-full w-full', className)}>
|
||||
<div ref={containerRef} data-testid="world-map" className="h-full w-full" />
|
||||
<MapLegend regions={regions} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+116
@@ -100,3 +100,119 @@
|
||||
background-color: var(--background);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Map popups (MapLibre renders these in the DOM, so style them here). */
|
||||
/* ------------------------------------------------------------------ */
|
||||
.maplibregl-popup-content {
|
||||
background: var(--popover);
|
||||
color: var(--popover-foreground);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 9px 11px;
|
||||
box-shadow: 0 10px 30px -10px rgb(0 0 0 / 0.7);
|
||||
font-size: 12px;
|
||||
line-height: 1.35;
|
||||
max-width: 230px;
|
||||
}
|
||||
.maplibregl-popup-tip {
|
||||
border-color: var(--popover) var(--popover) var(--border) var(--border);
|
||||
}
|
||||
.maplibregl-popup-close-button {
|
||||
color: var(--muted-foreground);
|
||||
font-size: 18px;
|
||||
padding: 0 6px;
|
||||
}
|
||||
.hm-popup-title {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.hm-popup-sub {
|
||||
color: var(--muted-foreground);
|
||||
font-size: 11px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.hm-popup-owner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.hm-popup-owner-big {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.hm-chip {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 3px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.hm-stats {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 4px 12px;
|
||||
margin-top: 7px;
|
||||
}
|
||||
.hm-stat {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
.hm-stat-k {
|
||||
color: var(--muted-foreground);
|
||||
font-size: 10px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
.hm-stat-v {
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Micro-interactions: event cards slide in + flash on arrival; the */
|
||||
/* "simulating" dot pulses. Kept here (map/feed-specific animation CSS).*/
|
||||
/* ------------------------------------------------------------------ */
|
||||
@keyframes hm-event-slide {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateY(-7px);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
@keyframes hm-event-flash {
|
||||
0% {
|
||||
box-shadow: 0 0 0 1px var(--primary), 0 0 22px -4px var(--primary);
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
.event-new {
|
||||
animation:
|
||||
hm-event-slide 0.35s ease-out,
|
||||
hm-event-flash 1.1s ease-out;
|
||||
}
|
||||
@keyframes hm-sim-pulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 0.35;
|
||||
transform: scale(0.7);
|
||||
}
|
||||
}
|
||||
.sim-pulse {
|
||||
animation: hm-sim-pulse 1.1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@@ -27,3 +27,14 @@ export const OUTCOME_COLORS: Record<EventOutcome, string> = {
|
||||
partial: '#f59e0b',
|
||||
neutral: '#94a3b8',
|
||||
};
|
||||
|
||||
/**
|
||||
* A 0–100 value → a color on a smooth red → yellow → green ramp, for stat bars.
|
||||
* Low values read as "danger" (red), high values as "strong" (green). Pure so the
|
||||
* dossier and any future gauge agree.
|
||||
*/
|
||||
export function statValueColor(v: number): string {
|
||||
const x = Math.max(0, Math.min(100, v));
|
||||
const hue = x * 1.2; // 0 → red, 60 → yellow, 120 → green
|
||||
return `hsl(${Math.round(hue)} 72% 46%)`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user