Files
blitzkit/src/app/tools/session/page.tsx
T

455 lines
15 KiB
TypeScript
Raw Normal View History

2023-09-18 22:32:21 +00:00
'use client';
import { CopyIcon, ListBulletIcon, ReloadIcon } from '@radix-ui/react-icons';
2023-09-18 23:05:19 +00:00
import { debounce } from 'lodash';
2023-09-23 21:51:00 +00:00
import { ChangeEvent, useEffect, useRef, useState } from 'react';
import * as Breakdown from '../../../components/Breakdown';
2023-09-18 22:32:21 +00:00
import { Button } from '../../../components/Button';
import PageWrapper from '../../../components/PageWrapper';
import { SearchBar } from '../../../components/SearchBar';
2023-09-24 15:58:42 -05:00
import { TreeTypeEnum } from '../../../components/Tanks';
2023-09-24 17:02:09 -05:00
import { REGION_NAMES, Region } from '../../../constants/regions';
2023-09-23 19:20:29 -05:00
import { WARGAMING_APPLICATION_ID } from '../../../constants/wargamingApplicationID';
2023-09-24 15:58:42 -05:00
import calculateWN8 from '../../../core/blitz/calculateWN8';
2023-09-23 21:51:00 +00:00
import { diffNormalizedTankStats } from '../../../core/blitz/diffNormalizedTankStats';
2023-09-24 15:58:42 -05:00
import getWN8Percentile from '../../../core/blitz/getWN8Percentile';
2023-09-23 19:20:29 -05:00
import getWargamingResponse from '../../../core/blitz/getWargamingResponse';
import listPlayers, {
AccountListWithServer,
} from '../../../core/blitz/listPlayers';
2023-09-24 15:58:42 -05:00
import { TankopediaEntry, tankopedia } from '../../../core/blitz/tankopedia';
import { tankAverages } from '../../../core/blitzstars/tankAverages';
2023-09-18 23:25:24 +00:00
import { theme } from '../../../stitches.config';
2023-09-19 15:52:39 +00:00
import { useSession } from '../../../stores/session';
2023-09-23 21:51:00 +00:00
import {
IndividualTankStats,
NormalizedTankStats,
2023-09-23 19:20:29 -05:00
TanksStats,
2023-09-23 21:51:00 +00:00
} from '../../../types/tanksStats';
2023-09-18 22:32:21 +00:00
import * as styles from './page.css';
2023-09-24 17:02:09 -05:00
// 1 once per 5 seconds
const REFRESH_RATE = 1 / 5;
2023-09-18 21:55:40 +00:00
export default function Page() {
2023-09-18 23:05:19 +00:00
const input = useRef<HTMLInputElement>(null);
2023-09-18 23:25:24 +00:00
const [searchResults, setSearchResults] = useState<
AccountListWithServer | undefined
>(undefined);
const [showSearchResults, setShowSearchResults] = useState(false);
2023-09-18 23:05:19 +00:00
const handleChange = debounce(
async (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.value) {
2023-09-23 19:20:29 -05:00
setSearchResults(await listPlayers(event.target.value));
2023-09-18 23:05:19 +00:00
} else {
setSearchResults(undefined);
setShowSearchResults(false);
2023-09-18 23:05:19 +00:00
}
},
500,
);
2023-09-23 21:51:00 +00:00
const session = useSession();
2023-09-24 17:02:09 -05:00
const tankStatsArray = session.isTracking
? (Object.values(session.tankStats) as IndividualTankStats[])
: [];
const since = session.isTracking ? new Date(session.time) : undefined;
2023-09-24 15:58:42 -05:00
const [diff, setDiff] = useState<
| {
2023-09-24 17:02:09 -05:00
careerWN8: number;
list: {
stats: IndividualTankStats;
tankopedia?: TankopediaEntry;
career: IndividualTankStats;
currentWN8?: number;
careerWN8?: number;
}[];
}
2023-09-24 15:58:42 -05:00
| undefined
>(undefined);
2023-09-23 21:51:00 +00:00
async function setSession(region: Region, id: number, nickname: string) {
input.current!.value = nickname;
const rawTankStats = (
await getWargamingResponse<TanksStats>(
`https://api.wotblitz.${region}/wotb/tanks/stats/?application_id=${WARGAMING_APPLICATION_ID}&account_id=${id}`,
)
)[id];
const tankStats = rawTankStats.reduce<NormalizedTankStats>(
(accumulator, tank) => ({
...accumulator,
[tank.tank_id]: tank,
}),
{},
);
useSession.setState({
isTracking: true,
id,
region,
nickname,
tankStats,
2023-09-28 10:39:32 -05:00
time: Date.now(),
});
}
2023-09-24 17:02:09 -05:00
useEffect(() => {
2023-09-28 10:39:32 -05:00
async function recalculateDiff() {
// const session = useSession.getState();
if (session.isTracking) {
const { id, region } = session;
const careerRaw = await getWargamingResponse<TanksStats>(
`https://api.wotblitz.${region}/wotb/tanks/stats/?application_id=${WARGAMING_APPLICATION_ID}&account_id=${id}`,
);
const career = careerRaw[id].reduce<
Record<number, IndividualTankStats>
>(
(accumulator, curr) => ({
...accumulator,
[curr.tank_id]: curr,
}),
{},
);
const awaitedTankopedia = await tankopedia;
const awaitedTankAverages = await tankAverages;
const careerWN8 =
careerRaw[id].reduce(
(accumulator, { tank_id, all }) =>
accumulator +
(awaitedTankAverages[tank_id] && all.battles > 0
? all.battles *
calculateWN8(awaitedTankAverages[tank_id].all, all)
: 0),
0,
) /
careerRaw[id].reduce(
(accumulator, { tank_id, all }) =>
accumulator +
(awaitedTankAverages[tank_id] && all.battles > 0
? all.battles
: 0),
0,
);
setDiff({
careerWN8,
list: (
Object.values(
diffNormalizedTankStats(session.tankStats, career),
) as IndividualTankStats[]
).map((stats) => {
return {
stats,
tankopedia: awaitedTankopedia[stats.tank_id],
career: career[stats.tank_id],
currentWN8: awaitedTankAverages[stats.tank_id]
? calculateWN8(
awaitedTankAverages[stats.tank_id].all,
stats.all,
)
: undefined,
careerWN8: awaitedTankAverages[stats.tank_id]
? calculateWN8(
awaitedTankAverages[stats.tank_id].all,
career[stats.tank_id].all,
)
: undefined,
};
}),
});
}
}
2023-09-24 17:02:09 -05:00
recalculateDiff();
const interval = setInterval(recalculateDiff, 1000 / REFRESH_RATE);
return () => clearInterval(interval);
2023-09-28 10:39:32 -05:00
}, [session]);
2023-09-18 23:05:19 +00:00
2023-09-28 10:28:22 -05:00
const battles = diff?.list.reduce(
(accumulator, { stats }) => accumulator + stats.all.battles,
0,
);
2023-09-18 22:32:21 +00:00
return (
<PageWrapper>
<div className={styles.toolBar}>
2023-09-18 23:25:24 +00:00
<div style={{ flex: 1, boxSizing: 'border-box', position: 'relative' }}>
<SearchBar
ref={input}
style={{ width: '100%', boxSizing: 'border-box' }}
2023-09-23 21:51:00 +00:00
defaultValue={session.isTracking ? session.nickname : undefined}
2023-09-18 23:25:24 +00:00
onChange={(event) => {
if (event.target.value) {
setShowSearchResults(true);
setSearchResults(undefined);
} else {
setShowSearchResults(false);
}
handleChange(event);
}}
placeholder="Search for a player..."
/>
{showSearchResults && (
<div
style={{
display: 'flex',
position: 'absolute',
width: '100%',
top: '100%',
marginTop: 8,
flexDirection: 'column',
backgroundColor: theme.colors.componentNonInteractive,
borderRadius: 4,
padding: 8,
boxSizing: 'border-box',
}}
>
{searchResults === undefined ? (
<div
style={{
display: 'flex',
alignContent: 'center',
justifyContent: 'center',
fontSize: 16,
color: theme.colors.textLowContrast,
}}
>
Searching...
</div>
) : searchResults.length === 0 ? (
<div
style={{
display: 'flex',
alignContent: 'center',
justifyContent: 'center',
fontSize: 16,
color: theme.colors.textLowContrast,
}}
>
No results
</div>
) : (
2023-09-19 15:52:39 +00:00
searchResults?.map(({ account_id: id, nickname, region }) => (
2023-09-18 23:25:24 +00:00
<button
2023-09-19 15:52:39 +00:00
key={id}
2023-09-18 23:25:24 +00:00
className={styles.searchButton}
onClick={() => {
setShowSearchResults(false);
setSession(region, id, nickname);
2023-09-18 23:25:24 +00:00
}}
>
<span
style={{
color: theme.colors.textHighContrast,
}}
>
{nickname}
</span>
<span
style={{
color: theme.colors.textLowContrast,
}}
>
{REGION_NAMES[region]}
</span>
</button>
))
)}
</div>
)}
</div>
2023-09-18 22:32:21 +00:00
<div style={{ display: 'flex', gap: 8 }}>
2023-09-19 15:52:39 +00:00
<Button
className={styles.toolbarButton}
color="dangerous"
onClick={async () => {
const session = useSession.getState();
if (!session.isTracking) return;
setSession(session.region, session.id, session.nickname);
2023-09-19 15:52:39 +00:00
}}
>
2023-09-18 22:32:21 +00:00
<ReloadIcon /> Reset
</Button>
2023-09-18 23:25:24 +00:00
<Button className={styles.toolbarButton}>
2023-09-18 22:32:21 +00:00
<CopyIcon /> Embed
</Button>
2023-09-18 23:25:24 +00:00
<Button className={styles.toolbarButton}>
2023-09-18 22:32:21 +00:00
<ListBulletIcon /> Options
</Button>
</div>
</div>
2023-09-23 21:51:00 +00:00
<Breakdown.Root>
2023-09-24 17:02:09 -05:00
{session.isTracking && since !== undefined && diff !== undefined && (
<Breakdown.Row
title={`Since ${since.toLocaleString(undefined, {
hour: 'numeric',
minute: 'numeric',
hour12: true,
month: 'short',
year: 'numeric',
day: 'numeric',
})}`}
stats={[
{
title: 'Battles',
2023-09-28 10:28:22 -05:00
current: battles!.toLocaleString(),
2023-09-24 17:02:09 -05:00
career: tankStatsArray
.reduce(
(accumulator, stats) => accumulator + stats.all.battles,
0,
)
.toLocaleString(),
},
{
title: 'Winrate',
2023-09-28 10:28:22 -05:00
current: battles
? `${(
100 *
(diff.list.reduce(
(accumulator, { stats }) =>
accumulator + stats.all.wins,
0,
) /
battles)
).toFixed(2)}%`
: '--',
2023-09-24 17:02:09 -05:00
career: `${(
100 *
(tankStatsArray.reduce(
(accumulator, stats) => accumulator + stats.all.wins,
0,
) /
tankStatsArray.reduce(
(accumulator, stats) => accumulator + stats.all.battles,
0,
))
).toFixed(2)}%`,
},
(() => {
2023-09-28 10:28:22 -05:00
const battlesWithWN8 = diff.list.reduce(
(accumulator, { currentWN8, stats }) =>
(currentWN8 === undefined ? 0 : stats.all.battles) +
accumulator,
0,
);
2023-09-24 17:02:09 -05:00
const currentWN8 =
diff.list.reduce(
(accumulator, { currentWN8, stats }) =>
stats.all.battles * (currentWN8 ?? 0) + accumulator,
0,
2023-09-28 10:28:22 -05:00
) / battlesWithWN8;
2023-09-24 17:02:09 -05:00
return {
title: 'WN8',
2023-09-28 10:28:22 -05:00
current: battlesWithWN8
? Math.round(currentWN8).toLocaleString()
: '--',
2023-09-28 10:39:32 -05:00
percentile: battlesWithWN8
? getWN8Percentile(currentWN8)
: undefined,
2023-09-24 17:02:09 -05:00
career: Math.round(diff.careerWN8).toLocaleString(),
};
})(),
{
title: 'Damage',
2023-09-28 10:28:22 -05:00
current: battles
? Math.round(
diff.list.reduce(
(accumulator, { stats }) =>
accumulator + stats.all.damage_dealt,
0,
) / battles,
).toLocaleString()
: '--',
2023-09-24 17:02:09 -05:00
career: Math.round(
tankStatsArray.reduce(
(accumulator, stats) =>
accumulator + stats.all.damage_dealt,
0,
) /
tankStatsArray.reduce(
(accumulator, stats) => accumulator + stats.all.battles,
0,
),
).toLocaleString(),
},
]}
/>
)}
{diff?.list
.sort((a, b) => b.stats.last_battle_time - a.stats.last_battle_time)
.map(({ stats, tankopedia, career, careerWN8, currentWN8 }) => (
<Breakdown.Row
key={stats.tank_id}
title={tankopedia?.name ?? `Unknown tank ${stats.tank_id}`}
type="tank"
tankType={tankopedia?.type}
treeType={(() => {
if (tankopedia?.is_collectible) return TreeTypeEnum.Collector;
if (tankopedia?.is_premium) return TreeTypeEnum.Premium;
})()}
stats={[
{
title: 'Battles',
current: stats.all.battles.toLocaleString(),
career: career.all.battles.toLocaleString(),
},
{
title: 'Winrate',
current: `${(
100 *
(stats.all.wins / stats.all.battles)
).toFixed(2)}%`,
career: `${(
100 *
(career.all.wins / career.all.battles)
).toFixed(2)}%`,
delta:
stats.all.wins / stats.all.battles -
career.all.wins / career.all.battles,
},
{
title: 'WN8',
current:
currentWN8 === undefined
? undefined
: Math.round(currentWN8).toLocaleString(),
career:
careerWN8 === undefined
? undefined
: Math.round(careerWN8).toLocaleString(),
percentile:
currentWN8 === undefined
? undefined
: getWN8Percentile(currentWN8),
},
{
title: 'Damage',
current: Math.round(
stats.all.damage_dealt / stats.all.battles,
).toLocaleString(),
career: Math.round(
career.all.damage_dealt / career.all.battles,
).toLocaleString(),
delta:
stats.all.damage_dealt / stats.all.battles -
career.all.damage_dealt / career.all.battles,
},
]}
/>
))}
2023-09-23 21:51:00 +00:00
</Breakdown.Root>
2023-09-18 22:32:21 +00:00
</PageWrapper>
);
2023-09-18 21:55:40 +00:00
}