add leaderboard pp chart

This commit is contained in:
Lee 2024-10-21 06:47:53 +01:00
parent 81640c3c4e
commit c3d4d1fe1f
4 changed files with 91 additions and 32 deletions

@ -4,7 +4,7 @@
import { Chart, registerables } from "chart.js"; import { Chart, registerables } from "chart.js";
import { Line } from "react-chartjs-2"; import { Line } from "react-chartjs-2";
import { useIsMobile } from "@/hooks/use-is-mobile"; import { useIsMobile } from "@/hooks/use-is-mobile";
import { formatDateMinimal, getDaysAgo, getDaysAgoDate, parseDate } from "@ssr/common/utils/time-utils"; import { formatDateMinimal, getDaysAgoDate, parseDate } from "@ssr/common/utils/time-utils";
Chart.register(...registerables); Chart.register(...registerables);
@ -16,7 +16,7 @@ export type Axis = {
position?: AxisPosition; position?: AxisPosition;
display?: boolean; display?: boolean;
grid?: { color?: string; drawOnChartArea?: boolean }; grid?: { color?: string; drawOnChartArea?: boolean };
title?: { display: boolean; text: string; color?: string }; title?: { display: boolean; text?: string; color?: string };
ticks?: { ticks?: {
stepSize?: number; stepSize?: number;
callback?: (value: number, index: number, values: any) => string; callback?: (value: number, index: number, values: any) => string;
@ -34,6 +34,7 @@ export type Dataset = {
lineTension: number; lineTension: number;
spanGaps: boolean; spanGaps: boolean;
yAxisID: string; yAxisID: string;
hidden?: boolean;
type?: DatasetDisplayType; type?: DatasetDisplayType;
}; };
@ -46,16 +47,17 @@ export type DatasetConfig = {
reverse: boolean; reverse: boolean;
display: boolean; display: boolean;
hideOnMobile?: boolean; hideOnMobile?: boolean;
displayName: string; displayName?: string;
position: AxisPosition; position: AxisPosition;
valueFormatter?: (value: number) => string; // Added precision option here valueFormatter?: (value: number) => string;
}; };
type?: DatasetDisplayType; type?: DatasetDisplayType;
labelFormatter: (value: number) => string; labelFormatter: (value: number) => string;
showLegend?: boolean;
}; };
export type ChartProps = { export type ChartProps = {
labels: Date[]; labels: Date[] | string[];
datasetConfig: DatasetConfig[]; datasetConfig: DatasetConfig[];
histories: Record<string, (number | null)[]>; histories: Record<string, (number | null)[]>;
}; };
@ -65,7 +67,7 @@ const generateAxis = (
reverse: boolean, reverse: boolean,
display: boolean, display: boolean,
position: AxisPosition, position: AxisPosition,
displayName: string, displayName?: string,
valueFormatter?: (value: number) => string valueFormatter?: (value: number) => string
): Axis => ({ ): Axis => ({
id, id,
@ -88,6 +90,7 @@ const generateDataset = (
data: (number | null)[], data: (number | null)[],
borderColor: string, borderColor: string,
yAxisID: string, yAxisID: string,
showLegend: boolean = true,
type?: DatasetDisplayType type?: DatasetDisplayType
): Dataset => ({ ): Dataset => ({
label, label,
@ -97,6 +100,7 @@ const generateDataset = (
lineTension: 0.5, lineTension: 0.5,
spanGaps: false, spanGaps: false,
yAxisID, yAxisID,
hidden: !showLegend, // Use hidden to disable legend
type, type,
...(type === "bar" && { ...(type === "bar" && {
backgroundColor: borderColor, backgroundColor: borderColor,
@ -112,7 +116,6 @@ export default function GenericChart({ labels, datasetConfig, histories }: Chart
reverse: false, reverse: false,
ticks: { ticks: {
font: (context: any) => { font: (context: any) => {
// Make the first of the month bold
if (parseDate(context.tick.label).getDate() === 1) { if (parseDate(context.tick.label).getDate() === 1) {
return { return {
weight: "bold", weight: "bold",
@ -143,7 +146,14 @@ export default function GenericChart({ labels, datasetConfig, histories }: Chart
config.axisConfig.valueFormatter config.axisConfig.valueFormatter
); );
return generateDataset(config.title, historyArray, config.color, config.axisId, config.type || "line"); return generateDataset(
config.title,
historyArray,
config.color,
config.axisId,
config.showLegend !== false, // Respect showLegend property
config.type || "line"
);
} }
return null; return null;
@ -157,27 +167,15 @@ export default function GenericChart({ labels, datasetConfig, histories }: Chart
scales: axes, scales: axes,
elements: { point: { radius: 0 } }, elements: { point: { radius: 0 } },
plugins: { plugins: {
legend: { position: "top", labels: { color: "white" } }, legend: {
tooltip: { position: "top",
callbacks: { labels: {
title(context: any) { color: "white",
const date = labels[context[0].dataIndex]; // Filter out datasets where showLegend is false
const differenceInDays = getDaysAgo(date); filter: (legendItem: any, chartData: any) => {
let formattedDate: string; // Access showLegend from chartData.datasets
if (differenceInDays === 0) { const dataset = chartData.datasets[legendItem.datasetIndex];
formattedDate = "Now"; return dataset.showLegend !== false; // Only show if showLegend is not false
} else if (differenceInDays === 1) {
formattedDate = "Yesterday";
} else {
formattedDate = formatDateMinimal(date);
}
return `${formattedDate} ${differenceInDays > 0 ? `(${differenceInDays} day${differenceInDays > 1 ? "s" : ""} ago)` : ""}`;
},
label(context: any) {
const value = Number(context.parsed.y);
const config = datasetConfig.find(cfg => cfg.title === context.dataset.label);
return config?.labelFormatter(value) ?? "";
}, },
}, },
}, },
@ -185,6 +183,9 @@ export default function GenericChart({ labels, datasetConfig, histories }: Chart
}; };
const formattedLabels = labels.map(date => { const formattedLabels = labels.map(date => {
if (typeof date === "string") {
return date;
}
const formattedDate = formatDateMinimal(date); const formattedDate = formatDateMinimal(date);
if (formatDateMinimal(getDaysAgoDate(0)) === formattedDate) { if (formatDateMinimal(getDaysAgoDate(0)) === formattedDate) {
return "Now"; return "Now";

@ -9,6 +9,7 @@ import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { fetchLeaderboard } from "@ssr/common/utils/leaderboard.util"; import { fetchLeaderboard } from "@ssr/common/utils/leaderboard.util";
import LeaderboardScoresResponse from "@ssr/common/response/leaderboard-scores-response"; import LeaderboardScoresResponse from "@ssr/common/response/leaderboard-scores-response";
import LeaderboardPpChart from "@/components/leaderboard/leaderboard-pp-chart";
const REFRESH_INTERVAL = 1000 * 60 * 5; const REFRESH_INTERVAL = 1000 * 60 * 5;
@ -48,17 +49,21 @@ export function LeaderboardData({ initialLeaderboard, initialScores, initialPage
} }
}, [data]); }, [data]);
const leaderboard = currentLeaderboard.leaderboard;
return ( return (
<main className="flex flex-col-reverse xl:flex-row w-full gap-2"> <main className="flex flex-col-reverse xl:flex-row w-full gap-2">
<LeaderboardScores <LeaderboardScores
leaderboard={currentLeaderboard.leaderboard} leaderboard={leaderboard}
initialScores={initialScores} initialScores={initialScores}
initialPage={initialPage} initialPage={initialPage}
leaderboardChanged={newId => setCurrentLeaderboardId(newId)} leaderboardChanged={newId => setCurrentLeaderboardId(newId)}
showDifficulties showDifficulties
isLeaderboardPage isLeaderboardPage
/> />
<LeaderboardInfo leaderboard={currentLeaderboard.leaderboard} beatSaverMap={currentLeaderboard.beatsaver} /> <div className="flex flex-col gap-2 w-full xl:w-[500px]">
<LeaderboardInfo leaderboard={leaderboard} beatSaverMap={currentLeaderboard.beatsaver} />
{leaderboard.stars > 0 && <LeaderboardPpChart leaderboard={leaderboard} />}
</div>
</main> </main>
); );
} }

@ -21,7 +21,7 @@ type LeaderboardInfoProps = {
export function LeaderboardInfo({ leaderboard, beatSaverMap }: LeaderboardInfoProps) { export function LeaderboardInfo({ leaderboard, beatSaverMap }: LeaderboardInfoProps) {
return ( return (
<Card className="xl:w-[500px] h-fit w-full"> <Card className="w-full h-fit">
<div className="flex flex-row justify-between w-full"> <div className="flex flex-row justify-between w-full">
<div className="flex flex-col justify-between w-full min-h-[160px]"> <div className="flex flex-col justify-between w-full min-h-[160px]">
{/* Song Info */} {/* Song Info */}

@ -0,0 +1,53 @@
"use client";
import React from "react";
import GenericChart, { DatasetConfig } from "@/components/chart/generic-chart";
import ScoreSaberLeaderboard from "@ssr/common/leaderboard/impl/scoresaber-leaderboard";
import { scoresaberService } from "@ssr/common/service/impl/scoresaber";
import Card from "@/components/card";
type Props = {
/**
* The player the chart is for
*/
leaderboard: ScoreSaberLeaderboard;
};
export default function LeaderboardPpChart({ leaderboard }: Props) {
const histories: Record<string, (number | null)[]> = {};
const labels: string[] = [];
for (let accuracy = 60; accuracy <= 100; accuracy += 0.2) {
const label = accuracy.toFixed(2) + "%";
labels.push(label);
const history = histories["pp"];
if (!history) {
histories["pp"] = [];
}
histories["pp"].push(scoresaberService.getPp(leaderboard.stars, accuracy));
}
const datasetConfig: DatasetConfig[] = [
{
title: "PP",
field: "pp",
color: "#3EC1D3",
axisId: "y",
axisConfig: {
reverse: false,
display: true,
displayName: "PP",
position: "left",
},
labelFormatter: (value: number) => `${value.toFixed(2)}pp`,
},
];
return (
<Card className="h-64 w-full">
<p className="font-semibold">PP Curve</p>
<GenericChart labels={labels} datasetConfig={datasetConfig} histories={histories} />
</Card>
);
}