profile and stats improvements

This commit is contained in:
yohlo
2025-09-13 23:05:35 -05:00
parent 4bc25fb0bc
commit d11e50d4ef
5 changed files with 171 additions and 69 deletions

View File

@@ -14,7 +14,8 @@ export const Route = createFileRoute("/_authed/stats")({
fullWidth: true,
header: {
title: "Player Stats"
}
},
refresh: [playerQueries.allStats().queryKey],
}),
});

View File

@@ -11,12 +11,15 @@ import {
Title,
ScrollArea,
Paper,
Popover,
ActionIcon,
} from "@mantine/core";
import {
MagnifyingGlassIcon,
CaretUpIcon,
CaretDownIcon,
ChartBarIcon,
InfoIcon,
} from "@phosphor-icons/react";
import { PlayerStats } from "../types";
import { motion } from "framer-motion";
@@ -25,7 +28,7 @@ interface PlayerStatsTableProps {
playerStats: PlayerStats[];
}
type SortKey = keyof PlayerStats;
type SortKey = keyof PlayerStats | 'mmr';
type SortDirection = 'asc' | 'desc';
interface SortConfig {
@@ -36,10 +39,42 @@ interface SortConfig {
const PlayerStatsTable = ({ playerStats }: PlayerStatsTableProps) => {
const [search, setSearch] = useState("");
const [sortConfig, setSortConfig] = useState<SortConfig>({
key: 'win_percentage',
key: 'mmr' as SortKey,
direction: 'desc'
});
// Calculate MMR (Match Making Rating) based on multiple factors
const calculateMMR = (stat: PlayerStats): number => {
if (stat.matches === 0) return 0;
// Base score from win percentage (0-100)
const winScore = stat.win_percentage;
// Match confidence factor (more matches = more reliable)
// Cap at 20 matches for full confidence
const matchConfidence = Math.min(stat.matches / 20, 1);
// Performance metrics
const avgCupsScore = Math.min(stat.avg_cups_per_match * 10, 100); // Cap at 10 avg cups
const marginScore = stat.margin_of_victory ? Math.min(stat.margin_of_victory * 20, 50) : 0; // Cap at 2.5 margin
// Volume bonus for active players (small bonus for playing more)
const volumeBonus = Math.min(stat.matches * 0.5, 10); // Max 10 point bonus
// Weighted calculation
const baseMMR = (
winScore * 0.5 + // Win % is 50% of score
avgCupsScore * 0.25 + // Avg cups is 25% of score
marginScore * 0.15 + // Win margin is 15% of score
volumeBonus * 0.1 // Volume bonus is 10% of score
);
// Apply confidence factor (players with few matches get penalized)
const finalMMR = baseMMR * matchConfidence;
return Math.round(finalMMR * 10) / 10; // Round to 1 decimal
};
const handleSort = (key: SortKey) => {
setSortConfig(prev => ({
key,
@@ -58,8 +93,17 @@ const PlayerStatsTable = ({ playerStats }: PlayerStatsTableProps) => {
);
return filtered.sort((a, b) => {
const aValue = a[sortConfig.key];
const bValue = b[sortConfig.key];
let aValue: number | string;
let bValue: number | string;
// Special handling for MMR
if (sortConfig.key === 'mmr') {
aValue = calculateMMR(a);
bValue = calculateMMR(b);
} else {
aValue = a[sortConfig.key];
bValue = b[sortConfig.key];
}
if (typeof aValue === 'number' && typeof bValue === 'number') {
return sortConfig.direction === 'desc' ? bValue - aValue : aValue - bValue;
@@ -79,7 +123,8 @@ const PlayerStatsTable = ({ playerStats }: PlayerStatsTableProps) => {
const formatDecimal = (value: number) => value.toFixed(2);
const columns = [
{ key: 'player_name' as SortKey, label: 'Player', width: 200 },
{ key: 'player_name' as SortKey, label: 'Player', width: 175 },
{ key: 'mmr' as SortKey, label: 'MMR', width: 90 },
{ key: 'win_percentage' as SortKey, label: 'Win %', width: 110 },
{ key: 'matches' as SortKey, label: 'Matches', width: 90 },
{ key: 'wins' as SortKey, label: 'Wins', width: 80 },
@@ -94,11 +139,15 @@ const PlayerStatsTable = ({ playerStats }: PlayerStatsTableProps) => {
const renderCellContent = (stat: PlayerStats, column: typeof columns[0], index: number) => {
switch (column.key) {
case 'player_name':
return <Text size='sm' fw={600}>{stat.player_name}</Text>
case 'mmr':
const mmr = calculateMMR(stat);
return (
<Group gap="sm">
<Text size="xs" c="dimmed" fw={500}>#{index + 1}</Text>
<Text fw={600}>{stat.player_name}</Text>
</Group>
<Box>
<Text fw={700} size="md" c={mmr >= 70 ? "green" : mmr >= 50 ? "blue" : mmr >= 30 ? "yellow" : "red"}>
{mmr.toFixed(1)}
</Text>
</Box>
);
case 'win_percentage':
return (
@@ -143,24 +192,19 @@ const PlayerStatsTable = ({ playerStats }: PlayerStatsTableProps) => {
return (
<Container size="100%" px={0}>
<Stack gap="lg">
<Group justify="space-between" align="flex-end" wrap="wrap">
<Stack gap="xs">
<Title order={2}>Player Statistics</Title>
<Text c="dimmed">
{filteredAndSortedStats.length} of {playerStats.length} players
</Text>
</Stack>
</Group>
<Stack gap="xs">
<Text ml='auto' size='xs' c="dimmed">
{filteredAndSortedStats.length} of {playerStats.length} players
</Text>
<TextInput
placeholder="Search players..."
placeholder="Search players"
value={search}
onChange={(e) => setSearch(e.currentTarget.value)}
leftSection={<MagnifyingGlassIcon size={16} />}
size="md"
/>
<Paper withBorder radius="md" p={0} style={{ overflow: 'hidden' }}>
<ScrollArea>
<Table
@@ -194,6 +238,9 @@ const PlayerStatsTable = ({ playerStats }: PlayerStatsTableProps) => {
backgroundColor: 'var(--mantine-color-body)',
borderBottom: '2px solid var(--mantine-color-default-border)',
...(index === 0 && {
position: 'sticky',
left: 0,
zIndex: 2,
borderTopLeftRadius: 'var(--mantine-radius-md)',
}),
...(index === columns.length - 1 && {
@@ -202,13 +249,63 @@ const PlayerStatsTable = ({ playerStats }: PlayerStatsTableProps) => {
}}
onClick={() => handleSort(column.key)}
>
<Group gap="xs" wrap="nowrap">
<Group gap="xs" wrap="nowrap" style={{ position: 'relative' }}>
<Text size="sm" fw={600}>
{column.label}
</Text>
{column.key === 'mmr' && (
<div
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
}}
onMouseDown={(e) => {
e.stopPropagation();
}}
>
<Popover position="bottom" withArrow shadow="md">
<Popover.Target>
<ActionIcon
variant="subtle"
size="xs"
>
<InfoIcon size={12} />
</ActionIcon>
</Popover.Target>
<Popover.Dropdown>
<Box maw={280}>
<Text size="sm" fw={500} mb="xs">MMR Calculation:</Text>
<Text size="xs" mb={2}> Win Rate (50%)</Text>
<Text size="xs" mb={2}> Average Cups/Match (25%)</Text>
<Text size="xs" mb={2}> Average Win Margin (15%)</Text>
<Text size="xs" mb={2}> Match Volume Bonus (10%)</Text>
<Text size="xs" mt="xs" c="dimmed">
* Confidence penalty applied for players with &lt;20 matches
</Text>
<Text size="xs" mt="xs" c="dimmed">
** Not an official rating
</Text>
</Box>
</Popover.Dropdown>
</Popover>
</div>
)}
<Box style={{ minWidth: 16, display: 'flex', justifyContent: 'center' }}>
{getSortIcon(column.key)}
</Box>
{index === 0 && (
<div
style={{
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
width: '2px',
backgroundColor: 'var(--mantine-color-default-border)',
zIndex: 1,
}}
/>
)}
</Group>
</Table.Th>
))}
@@ -225,15 +322,36 @@ const PlayerStatsTable = ({ playerStats }: PlayerStatsTableProps) => {
borderBottom: '1px solid var(--mantine-color-default-border)',
}}
>
{columns.map((column) => (
{columns.map((column, columnIndex) => (
<Table.Td
key={`${stat.id}-${column.key}`}
style={{
padding: '12px 16px',
verticalAlign: 'middle',
...(columnIndex === 0 && {
position: 'sticky',
left: 0,
backgroundColor: 'var(--mantine-color-body)',
zIndex: 1,
}),
}}
>
{renderCellContent(stat, column, index)}
<div style={{ position: 'relative' }}>
{renderCellContent(stat, column, index)}
{columnIndex === 0 && (
<div
style={{
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
width: '2px',
backgroundColor: 'var(--mantine-color-default-border)',
zIndex: 1,
}}
/>
)}
</div>
</Table.Td>
))}
</motion.tr>

View File

@@ -20,12 +20,24 @@ const Header = ({ player }: HeaderProps) => {
const owner = useMemo(() => authUser?.id === player.id, [authUser?.id, player.id]);
const name = useMemo(() => `${player.first_name} ${player.last_name}`, [player.first_name, player.last_name]);
const fontSize = useMemo(() => {
const baseSize = 24;
const maxLength = 20;
if (name.length <= maxLength) {
return `${baseSize}px`;
}
const scaleFactor = Math.max(0.6, maxLength / name.length);
return `${Math.floor(baseSize * scaleFactor)}px`;
}, [name]);
return (
<>
<Flex px='xl' w='100%' align='self-end' gap='md'>
<Avatar name={name} size={125} />
<Flex px='lg' w='100%' align='self-end' gap='md'>
<Avatar name={name} size={100} />
<Flex align='center' justify='center' gap={4} pb={20} w='100%'>
<Title ta='center' order={2}>{name}</Title>
<Title ta='center' style={{ fontSize, lineHeight: 1.2 }}>{name}</Title>
<ActionIcon display={owner ? 'block' : 'none'} radius='xl' variant='subtle' onClick={sheet.open}>
<PencilIcon size={20} />
</ActionIcon>

View File

@@ -30,7 +30,7 @@ const Profile = ({ id }: ProfileProps) => {
return (
<>
<Header player={player} />
<Box m="sm" mt="lg">
<Box m='md' mt="lg">
<SwipeableTabs tabs={tabs} />
</Box>
</>

View File

@@ -17,44 +17,15 @@ const StatCard = ({
value: number | null;
suffix?: string;
Icon?: Icon;
variant?: "default" | "featured" | "compact";
variant?: "default" | "compact";
}) => {
if (variant === "featured") {
return (
<Card
p="lg"
radius="lg"
style={{
background: 'linear-gradient(135deg, var(--mantine-color-blue-6) 0%, var(--mantine-color-blue-7) 100%)',
color: 'white',
border: 'none'
}}
>
<Stack gap="xs" align="center" ta="center">
{Icon && (
<ThemeIcon size="lg" variant="white" color="blue" radius="lg">
<Icon size={24} />
</ThemeIcon>
)}
<div>
<Text size="xl" fw={700} lh={1}>
{value !== null ? `${value}${suffix}` : "—"}
</Text>
<Text size="sm" opacity={0.9} fw={500} tt="uppercase" lts="0.5px">
{label}
</Text>
</div>
</Stack>
</Card>
);
}
if (variant === "compact") {
return (
<Card p="sm" radius="md" withBorder>
<Group justify="space-between" align="flex-start">
<Card p="xs" radius="md" withBorder>
<Group gap={2} justify="space-between" align="flex-start">
<Stack gap={2} flex={1}>
<Text size="xs" c="dimmed" fw={600} tt="uppercase" lts="0.3px">
<Text size='xs' c="dimmed" fw={600} tt="uppercase" lts="0.3px">
{label}
</Text>
<Text size="md" fw={700} lh={1}>
@@ -62,8 +33,8 @@ const StatCard = ({
</Text>
</Stack>
{Icon && (
<ThemeIcon size="md" variant="light" radius="md">
<Icon size={16} />
<ThemeIcon size="sm" variant="light" radius="md">
<Icon size={12} />
</ThemeIcon>
)}
</Group>
@@ -72,7 +43,7 @@ const StatCard = ({
}
return (
<Card p="md" radius="md" withBorder>
<Card p="sm" radius="md" withBorder>
<Stack gap="xs">
<Group justify="space-between" align="center">
<Text size="xs" c="dimmed" fw={600} tt="uppercase" lts="0.3px">
@@ -149,14 +120,14 @@ const StatsOverview = ({ playerId }: StatsOverviewProps) => {
};
return (
<Box p="md">
<Box>
<Stack gap="lg">
<Divider />
<Stack gap="sm">
<Text size="md" fw={600} c="dark">Match Statistics</Text>
<Grid gutter="md">
<Grid gutter="xs">
<Grid.Col span={4}>
<StatCard
label="Matches"
@@ -186,7 +157,7 @@ const StatsOverview = ({ playerId }: StatsOverviewProps) => {
<Stack gap="sm">
<Text size="md" fw={600} c="dark">Metrics</Text>
<Grid gutter="md">
<Grid gutter="xs">
<Grid.Col span={6}>
<StatCard
label="Cups Made"
@@ -217,14 +188,14 @@ const StatsOverview = ({ playerId }: StatsOverviewProps) => {
</Grid.Col>
<Grid.Col span={6}>
<StatCard
label="Avg Win Margin"
label="Win Margin"
value={avgMarginOfVictory > 0 ? parseFloat(avgMarginOfVictory.toFixed(1)) : null}
Icon={ArrowUpIcon}
/>
</Grid.Col>
<Grid.Col span={6}>
<StatCard
label="Avg Loss Margin"
label="Loss Margin"
value={avgMarginOfLoss > 0 ? parseFloat(avgMarginOfLoss.toFixed(1)) : null}
Icon={ArrowDownIcon}
/>