Feature: Live Map and Events Tab

This commit is contained in:
2025-11-02 20:59:28 +00:00
parent 4a8d6bc5d7
commit 8de538cc29
13 changed files with 1391 additions and 388 deletions
+265
View File
@@ -0,0 +1,265 @@
// components/dashboard/DashboardClient.tsx
'use client';
import { useEffect, useState } from 'react';
import { UsersIcon, ServerIcon, ActivityIcon, MapPinIcon, FlagIcon, LiveDotIcon, ClockIcon } from '@/components/ui/icons';
import { cleanTrackName, cleanTrackConfig } from '@/lib/trackUtils';
interface Driver {
driver_guid: string;
driver_name: string;
driver_team: string;
car_model: string;
car_skin: string;
laps_completed: number;
user_rank: number;
server: {
server_id: number;
server_name: string;
server_track: string;
server_config: string;
session_type: number;
session_flag: string;
session_time: number;
session_laps: number;
session_elapsed_time: number;
session_ambient_temp: number;
session_road_temp: number;
connected_players: number;
};
}
function getSessionTypeName(type: number): string {
switch (type) {
case 0: return 'PRACTICE';
case 1: return 'RACE';
case 2: return 'QUALIFYING';
default: return 'UNKNOWN';
}
}
function getSessionTypeColor(type: number): string {
switch (type) {
case 0: return 'border-blue-500/30 bg-blue-500/10 text-blue-400';
case 1: return 'border-red-500/30 bg-red-500/10 text-red-400';
case 2: return 'border-yellow-500/30 bg-yellow-500/10 text-yellow-400';
default: return 'border-white/20 bg-white/5 text-white/60';
}
}
function formatElapsedTime(ms: number): string {
const totalSeconds = Math.floor(ms / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) {
return `${hours}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}
return `${minutes}:${String(seconds).padStart(2, '0')}`;
}
export default function DashboardClient({ initialDrivers }: { initialDrivers: Driver[] }) {
const [drivers, setDrivers] = useState<Driver[]>(initialDrivers);
const [isLoading, setIsLoading] = useState(false);
// Auto-refresh every 3 seconds
useEffect(() => {
const fetchData = async () => {
try {
setIsLoading(true);
const response = await fetch('/api/dashboard');
const data = await response.json();
setDrivers(data.drivers);
} catch (error) {
console.error('[Dashboard] Failed to fetch data:', error);
} finally {
setIsLoading(false);
}
};
const interval = setInterval(fetchData, 3000);
return () => clearInterval(interval);
}, []);
// Group drivers by server
const serverGroups = drivers.reduce((acc, driver) => {
const serverId = driver.server?.server_id ?? 0;
if (!acc[serverId]) {
acc[serverId] = [];
}
acc[serverId].push(driver);
return acc;
}, {} as Record<number, Driver[]>);
return (
<>
{/* Stats Grid */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-12">
<StatCard
title="DRIVERS ONLINE"
value={drivers.length}
icon={<UsersIcon className="w-8 h-8" />}
pulse={isLoading}
/>
<StatCard
title="ACTIVE SERVERS"
value={Object.keys(serverGroups).length}
icon={<ServerIcon className="w-8 h-8" />}
pulse={isLoading}
/>
<StatCard
title="TOTAL LAPS"
value={drivers.reduce((sum, d) => sum + d.laps_completed, 0)}
icon={<ActivityIcon className="w-8 h-8" />}
pulse={isLoading}
/>
</div>
{/* Server Listings */}
<div className="max-w-7xl mx-auto px-6 py-12 space-y-6">
{Object.keys(serverGroups).length === 0 ? (
<div className="border border-white/10 p-16 text-center bg-black">
<div className="w-16 h-16 border-2 border-white/20 mx-auto mb-6"></div>
<p className="text-white/40 text-base tracking-wider">NO ACTIVE SESSIONS</p>
<p className="text-white/20 text-sm mt-2">System idle waiting for connections</p>
</div>
) : (
Object.entries(serverGroups).map(([serverId, serverDrivers]) => {
const server = serverDrivers[0].server;
return (
<div key={serverId} className="border border-white/10 sharp-border bg-black">
{/* Server Header */}
<div className="border-b border-white/10 p-6 topo-lines-dense">
<div className="flex items-start justify-between">
<div className="flex-1 space-y-3">
<div className="flex items-center space-x-3">
<div className="flex items-center space-x-2 px-2 py-1 border border-white/30 text-xs">
<LiveDotIcon className="w-2 h-2 animate-pulse" />
<span className="font-medium tracking-wider">LIVE</span>
</div>
<span className="text-xs text-white/40 tracking-wider">
ID: {server?.server_id}
</span>
</div>
<h2 className="text-2xl font-light tracking-tight" style={{ letterSpacing: "0.1em" }}>
{server?.server_name}
</h2>
<div className="flex flex-wrap gap-x-6 gap-y-2">
<div className="flex items-center space-x-2">
<MapPinIcon className="w-4 h-4 text-white/60" />
<span className="text-white/80 text-sm">
{cleanTrackName(server?.server_track || '')}
{server?.server_config && ` - ${cleanTrackConfig(server.server_config)}`}
</span>
</div>
<div className="flex items-center space-x-2">
<FlagIcon className="w-4 h-4 text-white/60" />
<span className="text-white/80 text-sm">{server?.session_flag}</span>
</div>
<div className="flex items-center space-x-2">
<UsersIcon className="w-4 h-4 text-white/60" />
<span className="text-white/80 text-sm">{server?.connected_players} CONNECTED</span>
</div>
</div>
</div>
{/* Session Info Badge */}
<div className="flex flex-col items-end space-y-2">
<div className={`px-3 py-2 border text-xs font-bold tracking-wider ${getSessionTypeColor(server?.session_type || 0)}`}>
{getSessionTypeName(server?.session_type || 0)}
</div>
<div className="flex items-center space-x-2 px-3 py-2 border border-white/20 bg-black text-xs">
<ClockIcon className="w-3 h-3 text-white/60" />
<span className="font-mono text-white/80">
{formatElapsedTime(server?.session_elapsed_time || 0)}
</span>
</div>
</div>
</div>
</div>
{/* Driver Table */}
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b border-white/10">
<th className="px-6 py-4 text-left text-xs font-bold tracking-wider text-white/60">POS</th>
<th className="px-6 py-4 text-left text-xs font-bold tracking-wider text-white/60">DRIVER</th>
<th className="px-6 py-4 text-left text-xs font-bold tracking-wider text-white/60">TEAM</th>
<th className="px-6 py-4 text-left text-xs font-bold tracking-wider text-white/60">CAR</th>
<th className="px-6 py-4 text-left text-xs font-bold tracking-wider text-white/60">RANK</th>
<th className="px-6 py-4 text-left text-xs font-bold tracking-wider text-white/60">LAPS</th>
</tr>
</thead>
<tbody>
{serverDrivers.map((driver, index) => (
<tr
key={driver.driver_guid}
className="border-b border-white/5 hover:bg-white/5 transition-colors"
>
<td className="px-6 py-4">
<span className="text-base font-bold tracking-tight">
{String(index + 1).padStart(2, '0')}
</span>
</td>
<td className="px-6 py-4">
<span className="font-semibold tracking-tight text-base">{driver.driver_name}</span>
</td>
<td className="px-6 py-4">
<span className="text-white/50 text-sm">
{driver.driver_team || '—'}
</span>
</td>
<td className="px-6 py-4">
<span className="text-white/70 text-sm font-mono tracking-tight">
{driver.car_model}
</span>
</td>
<td className="px-6 py-4">
<span className="inline-block px-3 py-1 border border-white/20 text-sm font-mono">
{driver.user_rank}
</span>
</td>
<td className="px-6 py-4">
<span className="font-mono text-sm">{driver.laps_completed}</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
})
)}
</div>
</>
);
}
function StatCard({
title,
value,
icon,
pulse
}: {
title: string;
value: number;
icon: React.ReactNode;
pulse?: boolean;
}) {
return (
<div className={`border border-white/10 p-6 sharp-border transition-opacity ${pulse ? 'opacity-70' : 'opacity-100'}`}>
<div className="flex items-center justify-between mb-4">
<span className="text-xs font-bold tracking-wider text-white/60">{title}</span>
<div className="text-white/40">
{icon}
</div>
</div>
<div className="text-5xl font-bold tracking-tight">
{value.toLocaleString()}
</div>
</div>
);
}
+144
View File
@@ -0,0 +1,144 @@
// components/events/EventResultsClient.tsx
'use client';
import { useEffect, useState } from 'react';
import { TrophyIcon, UsersIcon, FlagIcon } from '@/components/ui/icons';
interface TeamStanding {
team_id: number;
team_name: string;
total_points: number;
races_participated: number;
best_finish: number;
drivers: {
driver_guid: string;
driver_name: string;
position: number;
points_awarded: number;
dnf: boolean;
}[];
}
function getPositionColor(position: number): string {
if (position === 1) return 'bg-yellow-500/20 border-yellow-500/50 text-yellow-400';
if (position === 2) return 'bg-gray-400/20 border-gray-400/50 text-gray-300';
if (position === 3) return 'bg-orange-600/20 border-orange-600/50 text-orange-400';
return 'bg-white/5 border-white/10 text-white/60';
}
export default function EventResultsClient({
eventId,
initialStandings
}: {
eventId: string;
initialStandings: TeamStanding[]
}) {
const [standings, setStandings] = useState<TeamStanding[]>(initialStandings);
const [isLoading, setIsLoading] = useState(false);
// Auto-refresh every 5 seconds
useEffect(() => {
const fetchResults = async () => {
try {
setIsLoading(true);
const response = await fetch(`/api/events/${eventId}/results`);
const data = await response.json();
setStandings(data.standings);
} catch (error) {
console.error('[Results] Failed to fetch:', error);
} finally {
setIsLoading(false);
}
};
const interval = setInterval(fetchResults, 5000);
return () => clearInterval(interval);
}, [eventId]);
if (standings.length === 0) {
return (
<div className="border border-white/10 p-16 text-center bg-black">
<TrophyIcon className="w-16 h-16 mx-auto mb-6 text-white/20" />
<p className="text-white/40 text-base tracking-wider">NO RESULTS YET</p>
<p className="text-white/20 text-sm mt-2">Results will appear after the event concludes</p>
</div>
);
}
return (
<div className={`space-y-4 transition-opacity ${isLoading ? 'opacity-70' : 'opacity-100'}`}>
{standings.map((team: TeamStanding, index: number) => (
<div
key={team.team_id}
className={`border p-6 transition-all ${getPositionColor(index + 1)}`}
>
<div className="flex items-start justify-between mb-4">
<div className="flex items-center space-x-4">
{/* Position Badge */}
<div className="w-16 h-16 border-2 flex items-center justify-center">
<span className="text-3xl font-bold">
{index + 1}
</span>
</div>
{/* Team Info */}
<div>
<h2 className="text-2xl font-bold tracking-tight">
{team.team_name}
</h2>
<div className="flex items-center space-x-4 mt-2 text-sm text-white/60">
<div className="flex items-center space-x-1">
<UsersIcon className="w-4 h-4" />
<span>{team.drivers.length} {team.drivers.length === 1 ? 'Driver' : 'Drivers'}</span>
</div>
<div className="flex items-center space-x-1">
<FlagIcon className="w-4 h-4" />
<span>Best Finish: P{team.best_finish}</span>
</div>
</div>
</div>
</div>
{/* Total Points */}
<div className="text-right">
<div className="text-5xl font-bold tracking-tight">
{team.total_points}
</div>
<div className="text-sm text-white/60 tracking-wider">POINTS</div>
</div>
</div>
{/* Driver Results */}
<div className="border-t border-white/10 pt-4 mt-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{team.drivers.map((driver: any) => (
<div
key={driver.driver_guid}
className="flex items-center justify-between p-3 bg-black/30 border border-white/5"
>
<div className="flex items-center space-x-3">
<div className={`w-8 h-8 border flex items-center justify-center text-xs font-bold ${
driver.position <= 3 ? 'border-white/30' : 'border-white/10'
}`}>
P{driver.position}
</div>
<div>
<div className="font-semibold text-sm">{driver.driver_name}</div>
{driver.dnf && (
<div className="text-xs text-red-400">DNF</div>
)}
</div>
</div>
<div className="text-right">
<div className="font-bold text-lg">{driver.points_awarded}</div>
<div className="text-xs text-white/40">pts</div>
</div>
</div>
))}
</div>
</div>
</div>
))}
</div>
);
}
+1 -2
View File
@@ -8,10 +8,9 @@ export default function LiveRefreshWrapper({ children }: { children: React.React
const router = useRouter();
useEffect(() => {
// Refresh every 3 seconds for live updates
const interval = setInterval(() => {
router.refresh();
}, 3000);
}, 500);
return () => clearInterval(interval);
}, [router]);
+55 -7
View File
@@ -1,7 +1,7 @@
// components/live/LiveTiming.tsx
'use client';
import { BoltIcon } from '@/components/ui/icons';
import { BoltIcon, TrophyIcon } from '@/components/ui/icons';
interface TimingEntry {
position: number;
@@ -13,6 +13,8 @@ interface TimingEntry {
best_lap_time: number | null;
gap_to_leader: string;
avg_lap_time: number | null;
user_rank?: number | null; // Driver's position in rankings (1st, 2nd, etc.)
user_rating?: number | null; // Driver's rating score (ELO-style)
}
interface LiveTimingProps {
@@ -23,7 +25,7 @@ export default function LiveTiming({ entries }: LiveTimingProps) {
// Format lap time from milliseconds
const formatLapTime = (ms: number | null) => {
if (!ms || ms === 0) return '-:--.---';
if (!ms || ms === 0) return '--:--.---';
const minutes = Math.floor(ms / 60000);
const seconds = Math.floor((ms % 60000) / 1000);
@@ -32,14 +34,36 @@ export default function LiveTiming({ entries }: LiveTimingProps) {
return `${minutes}:${String(seconds).padStart(2, '0')}.${String(milliseconds).padStart(3, '0')}`;
};
// Format position with fallback
const formatPosition = (position: number | null | undefined) => {
if (!position || position === 0) return '--';
return String(position).padStart(2, '0');
};
// Format lap count with fallback
const formatLapCount = (laps: number | null | undefined) => {
if (!laps || laps === 0) return '--';
return laps;
};
// Get position color
const getPositionColor = (position: number) => {
if (!position || position === 0) return 'text-white/40 border-white/10';
if (position === 1) return 'text-white border-white';
if (position === 2) return 'text-white/90 border-white/70';
if (position === 3) return 'text-white/80 border-white/50';
return 'text-white/60 border-white/20';
};
// Get rank badge color
const getRankColor = (rank: number | null | undefined) => {
if (!rank) return 'bg-white/10 text-white/40';
if (rank <= 10) return 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30';
if (rank <= 50) return 'bg-blue-500/20 text-blue-400 border-blue-500/30';
if (rank <= 100) return 'bg-green-500/20 text-green-400 border-green-500/30';
return 'bg-white/10 text-white/60 border-white/20';
};
return (
<div className="space-y-2">
{/* Header */}
@@ -56,7 +80,8 @@ export default function LiveTiming({ entries }: LiveTimingProps) {
{entries.map((entry) => {
const isLeader = entry.position === 1;
const isFastestLap = entries.length > 0 &&
entry.best_lap_time === Math.min(...entries.filter(e => e.best_lap_time).map(e => e.best_lap_time!));
entry.best_lap_time && entry.best_lap_time > 0 &&
entry.best_lap_time === Math.min(...entries.filter(e => e.best_lap_time && e.best_lap_time > 0).map(e => e.best_lap_time!));
return (
<div
@@ -71,19 +96,35 @@ export default function LiveTiming({ entries }: LiveTimingProps) {
{/* Position */}
<div className="col-span-1 flex items-center">
<span className="text-lg font-bold">
{String(entry.position).padStart(2, '0')}
{formatPosition(entry.position)}
</span>
</div>
{/* Driver Info */}
<div className="col-span-4 flex flex-col justify-center">
<div className="font-normal truncate" style={{ letterSpacing: "0.1em" }}>{entry.driver_name}</div>
<div className="flex items-center space-x-2">
<span className="font-normal truncate" style={{ letterSpacing: "0.1em" }}>
{entry.driver_name}
</span>
{entry.user_rank && (
<div className="flex items-center space-x-1">
<span className={`text-[10px] px-1.5 py-0.5 border rounded ${getRankColor(entry.user_rank)}`}>
#{entry.user_rank}
</span>
{entry.user_rating && (
<span className="text-[10px] text-white/40 font-mono">
{entry.user_rating}
</span>
)}
</div>
)}
</div>
<div className="text-xs text-white/40 font-mono truncate">{entry.car_model}</div>
</div>
{/* Current Lap */}
<div className="col-span-2 flex items-center justify-end">
<span className="font-mono text-sm">{entry.current_lap}</span>
<span className="font-mono text-sm">{formatLapCount(entry.current_lap)}</span>
</div>
{/* Last Lap Time */}
@@ -91,7 +132,7 @@ export default function LiveTiming({ entries }: LiveTimingProps) {
<div className="font-mono text-sm">
{formatLapTime(entry.last_lap_time)}
</div>
{entry.avg_lap_time && (
{entry.avg_lap_time && entry.avg_lap_time > 0 && (
<div className="text-xs text-white/40 font-mono">
Avg: {formatLapTime(entry.avg_lap_time)}
</div>
@@ -118,7 +159,14 @@ export default function LiveTiming({ entries }: LiveTimingProps) {
<BoltIcon className="w-3 h-3" />
<span>Fastest lap overall</span>
</div>
<div className="flex items-center space-x-2">
<span className="text-[10px] px-1.5 py-0.5 border rounded bg-yellow-500/20 text-yellow-400 border-yellow-500/30">
#1-10
</span>
<span>Top 10 ranked driver</span>
</div>
<div>Times updated in real-time from server telemetry</div>
<div className="text-white/30 text-[11px]">-- indicates driver has not started or is in pits</div>
</div>
</div>
);
+82 -26
View File
@@ -3,6 +3,7 @@
import { useEffect, useState } from 'react';
import { getTrackMapUrl, cleanTrackName, cleanTrackConfig } from '@/lib/trackUtils';
import { getTrackMapConfig, worldToMapCoords, type TrackMapConfig } from '@/lib/trackMapConfig';
interface Car {
carID: number;
@@ -12,6 +13,7 @@ interface Car {
position: number;
lap_time?: number;
best_lap_time?: number;
world_position?: { x: number; y: number; z: number };
}
interface LiveTrackMapProps {
@@ -22,31 +24,79 @@ interface LiveTrackMapProps {
export default function LiveTrackMap({ track, trackConfig, cars }: LiveTrackMapProps) {
const [imageError, setImageError] = useState(false);
const [mapConfig, setMapConfig] = useState<TrackMapConfig | null>(null);
// Get cleaned track map URL
// Static track bounds - set once and never change
const [trackBounds, setTrackBounds] = useState<{
minX: number;
maxX: number;
minZ: number;
maxZ: number;
} | null>(null);
// Add mouse position state
const [mousePos, setMousePos] = useState<{ x: number; y: number } | null>(null);
// Define event handlers
const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
const rect = e.currentTarget.getBoundingClientRect();
const x = ((e.clientX - rect.left) / rect.width) * 100;
const y = ((e.clientY - rect.top) / rect.height) * 100;
setMousePos({ x, y });
};
const handleMouseLeave = () => {
setMousePos(null);
};
const trackMapUrl = getTrackMapUrl(track, trackConfig);
const displayTrackName = cleanTrackName(track);
const displayTrackConfig = cleanTrackConfig(trackConfig);
// Calculate position on track (circular approximation)
const getCarPosition = (normalizedPos: number) => {
// normalizedPos is 0.0 to 1.0 around the track
// We'll place cars in a circular path for now
const angle = normalizedPos * Math.PI * 2 - Math.PI / 2; // Start at top
// Position relative to center (percentage)
const centerX = 50;
const centerY = 50;
const radius = 40; // 40% from center
const x = centerX + Math.cos(angle) * radius;
const y = centerY + Math.sin(angle) * radius;
return { x, y };
useEffect(() => {
getTrackMapConfig(track, trackConfig).then(config => {
setMapConfig(config);
if (config) {
const halfWidth = config.width / 2;
const halfHeight = config.height / 2;
setTrackBounds({
minX: config.xOffset - halfWidth,
maxX: config.xOffset + halfWidth,
minZ: config.zOffset - halfHeight,
maxZ: config.zOffset + halfHeight,
});
}
});
}, [track, trackConfig]);
// Convert world position to screen position
const getCarPosition = (car: Car) => {
// Use AC's formula with map.ini config
if (car.world_position && car.world_position.x !== undefined && mapConfig) {
const pos = worldToMapCoords(
car.world_position.x,
car.world_position.y,
car.world_position.z,
mapConfig
);
// Debug first car only
if (cars.indexOf(car) === 0) {
console.log(`[Map] World: (${car.world_position.x.toFixed(1)}, ${car.world_position.z.toFixed(1)}) -> Screen: (${pos.x.toFixed(1)}%, ${pos.y.toFixed(1)}%)`);
}
return pos;
}
// Fallback: distribute along diagonal based on normalizedSplinePos
const fallbackX = car.normalizedSplinePos * 100;
const fallbackY = car.normalizedSplinePos * 100;
return { x: fallbackX, y: fallbackY };
};
// Get color based on position
const getPositionColor = (position: number) => {
if (!position || position === 0) return '#6b7280'; // Gray for no position
if (position === 1) return '#ffffff'; // P1 - White
if (position === 2) return '#d1d5db'; // P2 - Light gray
if (position === 3) return '#9ca3af'; // P3 - Gray
@@ -54,7 +104,11 @@ export default function LiveTrackMap({ track, trackConfig, cars }: LiveTrackMapP
};
return (
<div className="relative w-full aspect-square bg-black border border-white/10 overflow-hidden">
<div
className="relative w-full aspect-square bg-black border border-white/10 overflow-hidden"
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
{/* Track Map Background */}
{!imageError ? (
<img
@@ -84,9 +138,9 @@ export default function LiveTrackMap({ track, trackConfig, cars }: LiveTrackMapP
{/* Car Positions */}
<div className="absolute inset-0">
{cars.map((car) => {
const pos = getCarPosition(car.normalizedSplinePos);
const pos = getCarPosition(car);
const color = getPositionColor(car.position);
return (
<div
key={car.carID}
@@ -106,14 +160,16 @@ export default function LiveTrackMap({ track, trackConfig, cars }: LiveTrackMapP
boxShadow: `0 0 10px ${color}`,
}}
/>
{/* Position number */}
<div
className="absolute -top-6 left-1/2 transform -translate-x-1/2 text-xs font-bold whitespace-nowrap px-2 py-1 bg-black/80 border"
style={{ borderColor: color, color: color }}
>
P{car.position}
</div>
{car.position > 0 && (
<div
className="absolute -top-6 left-1/2 transform -translate-x-1/2 text-xs font-bold whitespace-nowrap px-2 py-1 bg-black/80 border"
style={{ borderColor: color, color: color }}
>
P{car.position}
</div>
)}
{/* Driver name on hover */}
<div className="absolute top-6 left-1/2 transform -translate-x-1/2 opacity-0 hover:opacity-100 transition-opacity whitespace-nowrap">