revert to client sided data fetching
All checks were successful
deploy / deploy (push) Successful in 47s

This commit is contained in:
Lee 2023-10-24 11:18:51 +01:00
parent fe0be93d3e
commit e77e07423a
15 changed files with 700 additions and 573 deletions

@ -1,124 +0,0 @@
import Card from "@/components/Card";
import Container from "@/components/Container";
import Error from "@/components/Error";
import PlayerInfo from "@/components/player/PlayerInfo";
import Scores from "@/components/player/Scores";
import { ssrSettings } from "@/ssrSettings";
import { SortTypes } from "@/types/SortTypes";
import { formatNumber } from "@/utils/number";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
import { normalizedRegionName } from "@/utils/utils";
import { Metadata } from "next";
type PlayerPageProps = {
params: { id: string; leaderboard: string; sort: string; page: string };
};
const DEFAULT_SORT_TYPE = SortTypes.top;
// Get data from API (server-sided)
async function getData(playerId: string, sort?: string, page?: number) {
const playerData = await ScoreSaberAPI.fetchPlayerData(playerId);
if (!playerData) {
return undefined;
}
const scores = [];
let totalPages = -1;
if (sort && page) {
const scoresData = await ScoreSaberAPI.fetchScores(
playerId,
page,
sort,
10,
);
if (scoresData) {
scores.push(...scoresData.scores);
totalPages = scoresData.pageInfo.totalPages;
}
}
return { player: playerData, scores: scores, totalPages: totalPages };
}
export async function generateMetadata({
params: { id, leaderboard, sort, page },
}: PlayerPageProps): Promise<Metadata> {
const data = await getData(id, sort, Number(page));
if (!data) {
return {
title: "Player not found",
};
}
const player = data.player;
const description = `
View ${player.name}'s scores, top plays, and more.
Rank: #${formatNumber(player.rank)} (#${formatNumber(
player.countryRank,
)} - ${normalizedRegionName(player.country)})
PP: ${formatNumber(player.pp)}
Play Count: ${formatNumber(player.scoreStats.totalPlayCount)}`;
return {
title: `${player.name}`,
description: `View ${player.name}'s scores, top plays, and more.`,
openGraph: {
siteName: ssrSettings.siteName,
title: `${player.name}`,
description: description,
images: [
{
url: player.profilePicture,
},
],
},
twitter: {
card: "summary",
},
};
}
export default async function Player({
params: { id, leaderboard, sort, page },
}: PlayerPageProps) {
const playerData = await getData(id, sort, Number(page));
const currentPage = Number(page);
const sortType = SortTypes[sort] || DEFAULT_SORT_TYPE;
if (!playerData) {
return (
<main>
<Container>
<Card className="mt-2">
<Error errorMessage="Failed to load player. Is the ID valid?" />
</Card>
</Container>
</main>
);
}
const player = playerData.player;
const scores = playerData.scores;
return (
<main>
<Container>
<Card className="mt-2">
<PlayerInfo playerData={player} />
</Card>
<Card className="mt-2">
<Scores
playerData={player}
page={currentPage}
sortType={sortType}
scores={scores}
totalPages={playerData.totalPages}
/>
</Card>
</Container>
</main>
);
}

@ -0,0 +1,52 @@
import PlayerPage from "@/components/player/PlayerPage";
import { ssrSettings } from "@/ssrSettings";
import { formatNumber } from "@/utils/number";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
import { normalizedRegionName } from "@/utils/utils";
import { Metadata } from "next";
type Props = {
params: { id: string };
};
export async function generateMetadata({
params: { id },
}: Props): Promise<Metadata> {
const player = await ScoreSaberAPI.fetchPlayerData(id);
if (!player) {
return {
title: "Player not found",
};
}
const description = `
View ${player.name}'s scores, top plays, and more.
Rank: #${formatNumber(player.rank)} (#${formatNumber(
player.countryRank,
)} - ${normalizedRegionName(player.country)})
PP: ${formatNumber(player.pp)}
Play Count: ${formatNumber(player.scoreStats.totalPlayCount)}`;
return {
title: `${player.name}`,
description: `View ${player.name}'s scores, top plays, and more.`,
openGraph: {
siteName: ssrSettings.siteName,
title: `${player.name}`,
description: description,
images: [
{
url: player.profilePicture,
},
],
},
twitter: {
card: "summary",
},
};
}
export default function Player({ params: { id } }: Props) {
return <PlayerPage id={id} />;
}

@ -1,44 +0,0 @@
import Card from "@/components/Card";
import Container from "@/components/Container";
import Error from "@/components/Error";
import GlobalRanking from "@/components/player/GlobalRanking";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
type RankingGlobalProps = {
params: { page: string; country: string };
};
// Get data from API (server-sided)
async function getData(page: number, country: string) {
const pageData = await ScoreSaberAPI.fetchTopPlayers(page, country);
if (!pageData) {
return undefined;
}
return pageData;
}
export default async function RankingGlobal({
params: { page, country },
}: RankingGlobalProps) {
const pageData = await getData(Number(page), country);
return (
<main>
<Container>
<Card className="mt-2">
{pageData == undefined && (
<Error errorMessage="Failed to load players. Is the page valid?" />
)}
{pageData && (
<GlobalRanking
page={Number(page)}
players={pageData.players}
totalPages={pageData.pageInfo.totalPages}
country={country}
/>
)}
</Card>
</Container>
</main>
);
}

@ -0,0 +1,14 @@
import GlobalRanking from "@/components/player/GlobalRanking";
import { getPageFromSearchQuery } from "@/utils/utils";
import { headers } from "next/headers";
type RankingCountryProps = {
params: { country: string };
};
export default function RankingCountry({ params }: RankingCountryProps) {
const page = getPageFromSearchQuery(headers());
const country = params.country;
return <GlobalRanking page={page} country={country} />;
}

@ -1,43 +0,0 @@
import Card from "@/components/Card";
import Container from "@/components/Container";
import Error from "@/components/Error";
import GlobalRanking from "@/components/player/GlobalRanking";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
type RankingGlobalProps = {
params: { page: string };
};
// Get data from API (server-sided)
async function getData(page: number) {
const pageData = await ScoreSaberAPI.fetchTopPlayers(page);
if (!pageData || pageData.players.length == 0) {
return undefined;
}
return pageData;
}
export default async function RankingGlobal({
params: { page },
}: RankingGlobalProps) {
const pageData = await getData(Number(page));
return (
<main>
<Container>
<Card className="mt-2">
{pageData == undefined && (
<Error errorMessage="Failed to load players. Is the page valid?" />
)}
{pageData && (
<GlobalRanking
page={Number(page)}
players={pageData.players}
totalPages={pageData.pageInfo.totalPages}
/>
)}
</Card>
</Container>
</main>
);
}

@ -0,0 +1,9 @@
import GlobalRanking from "@/components/player/GlobalRanking";
import { getPageFromSearchQuery } from "@/utils/utils";
import { headers } from "next/headers";
export default function RankingGlobal() {
const page = getPageFromSearchQuery(headers());
return <GlobalRanking page={page} />;
}

@ -43,23 +43,20 @@ function NavbarButton({ text, icon, href, children }: ButtonProps) {
export default function Navbar() { export default function Navbar() {
const settingsStore = useStore(useSettingsStore, (state) => state); const settingsStore = useStore(useSettingsStore, (state) => state);
const player = settingsStore?.player;
const lastUsedSortType = settingsStore?.lastUsedSortType.value;
return ( return (
<> <>
<div className="flex h-fit w-full rounded-md bg-gray-800"> <div className="flex h-fit w-full rounded-md bg-gray-800">
{settingsStore !== undefined && player && ( {settingsStore !== undefined && settingsStore.player && (
<NavbarButton <NavbarButton
text="You" text="You"
icon={ icon={
<Avatar <Avatar
url={player.profilePicture} url={settingsStore.player.profilePicture}
label="Your avatar" label="Your avatar"
size={32} size={32}
/> />
} }
href={`/player/${player?.id}/scoresaber/${lastUsedSortType}/1`} href={`/player/${settingsStore.player.id}`}
/> />
)} )}
@ -73,7 +70,7 @@ export default function Navbar() {
key={friend.id} key={friend.id}
className="mt-2 bg-gray-500" className="mt-2 bg-gray-500"
text={friend.name} text={friend.name}
url={`/player/${friend.id}/scoresaber/${lastUsedSortType}/1`} url={`/player/${friend.id}`}
icon={ icon={
<Avatar <Avatar
url={friend.profilePicture} url={friend.profilePicture}

@ -1,100 +1,186 @@
"use client"; "use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player"; import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
import { normalizedRegionName } from "@/utils/utils"; import { normalizedRegionName } from "@/utils/utils";
import dynamic from "next/dynamic"; import dynamic from "next/dynamic";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import Card from "../Card";
import Container from "../Container";
import Pagination from "../Pagination"; import Pagination from "../Pagination";
import Spinner from "../Spinner";
import PlayerRanking from "./PlayerRanking"; import PlayerRanking from "./PlayerRanking";
import PlayerRankingMobile from "./PlayerRankingMobile"; import PlayerRankingMobile from "./PlayerRankingMobile";
const ReactCountryFlag = dynamic(() => import("react-country-flag")); const ReactCountryFlag = dynamic(() => import("react-country-flag"));
const Error = dynamic(() => import("@/components/Error"));
type GlobalRankingProps = { type PageInfo = {
loading: boolean;
page: number; page: number;
totalPages: number; totalPages: number;
country?: string;
players: ScoresaberPlayer[]; players: ScoresaberPlayer[];
}; };
export default function GlobalRanking({ type GlobalRankingProps = {
page, page: number;
totalPages, country?: string;
country, };
players,
}: GlobalRankingProps) { export default function GlobalRanking({ page, country }: GlobalRankingProps) {
const router = useRouter(); const router = useRouter();
return ( const [error, setError] = useState(false);
<> const [errorMessage, setErrorMessage] = useState("");
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 rounded-md bg-gray-700 p-2">
{country && (
<ReactCountryFlag countryCode={country} svg className="!h-8 !w-8" />
)}
<p>
You are viewing{" "}
{country
? "scores from " + normalizedRegionName(country)
: "Global scores"}
</p>
</div>
<table className="hidden w-full table-auto border-spacing-2 border-none text-left md:table"> const [pageInfo, setPageInfo] = useState<PageInfo>({
<thead> loading: true,
<tr> page: page,
<th className="px-4 py-2">Rank</th> totalPages: 1,
<th className="px-4 py-2">Profile</th> players: [],
<th className="px-4 py-2">Performance Points</th> });
<th className="px-4 py-2">Total Plays</th>
<th className="px-4 py-2">Total Ranked Plays</th>
<th className="px-4 py-2">Avg Ranked Accuracy</th>
</tr>
</thead>
<tbody className="border-none">
{players.map((player) => (
<tr key={player.rank} className="border-b border-gray-700">
<PlayerRanking
showCountryFlag={country ? false : true}
player={player}
/>
</tr>
))}
</tbody>
</table>
<div className="flex flex-col gap-2 md:hidden"> const updatePage = useCallback(
{players.map((player) => ( (page: any) => {
<div console.log("Switching page to", page);
key={player.rank} ScoreSaberAPI.fetchTopPlayers(page, country).then((response) => {
className="flex flex-col gap-2 rounded-md bg-gray-700 hover:bg-gray-600" if (!response) {
> setError(true);
<Link href={`/player/${player.id}`}> setErrorMessage("No players found");
<PlayerRankingMobile player={player} /> setPageInfo({ ...pageInfo, loading: false });
</Link> return;
}
setPageInfo({
...pageInfo,
players: response.players,
totalPages: response.pageInfo.totalPages,
loading: false,
page: page,
});
const urlBase = country
? `/ranking/country/${country}`
: "/ranking/global";
if (page > 1) {
router.push(`${urlBase}?page=${page}`, {
scroll: false,
});
} else {
router.push(`${urlBase}`, {
scroll: false,
});
}
});
},
[country, pageInfo, router],
);
useEffect(() => {
if (!pageInfo.loading || error) return;
updatePage(pageInfo.page);
}, [error, country, updatePage, pageInfo.page, pageInfo.loading]);
if (pageInfo.loading || error) {
return (
<main>
<Container>
<Card className="mt-2">
<div className="p-3 text-center">
<div role="status">
<div className="flex flex-col items-center justify-center gap-2">
{error && <Error errorMessage={errorMessage} />}
{!error && <Spinner />}
</div>
</div>
</div> </div>
))} </Card>
</div> </Container>
</main>
);
}
{/* Pagination */} const players = pageInfo.players;
<div className="flex w-full flex-row justify-center rounded-md bg-gray-800 md:flex-col">
<div className="p-3"> return (
<Pagination <main>
currentPage={page} <Container>
totalPages={totalPages} <Card className="mt-2">
onPageChange={(page) => { {pageInfo.loading ? (
const urlBase = country <div className="flex justify-center">
? `/ranking/country/${country}` <Spinner />
: `/ranking/global`; </div>
router.push(`${urlBase}/${page}`, { ) : (
scroll: false, <div className="flex flex-col gap-2">
}); <div className="flex items-center gap-2 rounded-md bg-gray-700 p-2">
}} {country && (
/> <ReactCountryFlag
</div> countryCode={country}
</div> svg
</div> className="!h-8 !w-8"
</> />
)}
<p>
You are viewing{" "}
{country
? "scores from " + normalizedRegionName(country)
: "Global scores"}
</p>
</div>
<table className="hidden w-full table-auto border-spacing-2 border-none text-left md:table">
<thead>
<tr>
<th className="px-4 py-2">Rank</th>
<th className="px-4 py-2">Profile</th>
<th className="px-4 py-2">Performance Points</th>
<th className="px-4 py-2">Total Plays</th>
<th className="px-4 py-2">Total Ranked Plays</th>
<th className="px-4 py-2">Avg Ranked Accuracy</th>
</tr>
</thead>
<tbody className="border-none">
{players.map((player) => (
<tr key={player.rank} className="border-b border-gray-700">
<PlayerRanking
showCountryFlag={country ? false : true}
player={player}
/>
</tr>
))}
</tbody>
</table>
<div className="flex flex-col gap-2 md:hidden">
{players.map((player) => (
<div
key={player.rank}
className="flex flex-col gap-2 rounded-md bg-gray-700 hover:bg-gray-600"
>
<Link href={`/player/${player.id}`}>
<PlayerRankingMobile player={player} />
</Link>
</div>
))}
</div>
{/* Pagination */}
<div className="flex w-full flex-row justify-center rounded-md bg-gray-800 md:flex-col">
<div className="p-3">
<Pagination
currentPage={pageInfo.page}
totalPages={pageInfo.totalPages}
onPageChange={(page) => {
updatePage(page);
}}
/>
</div>
</div>
</div>
)}
</Card>
</Container>
</main>
); );
} }

@ -1,5 +1,3 @@
"use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player"; import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { useScoresaberScoresStore } from "@/store/scoresaberScoresStore"; import { useScoresaberScoresStore } from "@/store/scoresaberScoresStore";
import { useSettingsStore } from "@/store/settingsStore"; import { useSettingsStore } from "@/store/settingsStore";
@ -8,6 +6,7 @@ import {
calcPpBoundary, calcPpBoundary,
getAveragePp, getAveragePp,
getHighestPpPlay, getHighestPpPlay,
getTotalScores,
} from "@/utils/scoresaber/scores"; } from "@/utils/scoresaber/scores";
import { import {
GlobeAsiaAustraliaIcon, GlobeAsiaAustraliaIcon,
@ -20,6 +19,7 @@ import { useRef } from "react";
import { toast } from "react-toastify"; import { toast } from "react-toastify";
import { useStore } from "zustand"; import { useStore } from "zustand";
import Avatar from "../Avatar"; import Avatar from "../Avatar";
import Card from "../Card";
import Label from "../Label"; import Label from "../Label";
const PlayerChart = dynamic(() => import("./PlayerChart")); const PlayerChart = dynamic(() => import("./PlayerChart"));
@ -96,6 +96,10 @@ export default function PlayerInfo({ playerData }: PlayerInfoProps) {
}); });
} }
} }
console.log(
`Fetching scores for ${playerId} (${page}/${totalPages})`,
);
}, },
); );
if (reponse?.error) { if (reponse?.error) {
@ -109,138 +113,147 @@ export default function PlayerInfo({ playerData }: PlayerInfoProps) {
const isOwnProfile = settingsStore.player?.id == playerId; const isOwnProfile = settingsStore.player?.id == playerId;
return ( return (
<div className="flex flex-col items-center gap-3 md:flex-row md:items-start"> <Card className="mt-2">
<div className="min-w-fit"> {/* Player Info */}
{/* Avatar */} <div className="flex flex-col items-center gap-3 md:flex-row md:items-start">
<div className="flex flex-col items-center gap-2"> <div className="min-w-fit">
<Avatar url={playerData.profilePicture} label="Avatar" /> {/* Avatar */}
<div className="flex flex-col items-center gap-2">
<Avatar url={playerData.profilePicture} label="Avatar" />
</div>
{/* Settings Buttons */}
<div className="absolute right-3 top-20 flex flex-col justify-end gap-2 md:relative md:right-0 md:top-0 md:mt-2 md:flex-row md:justify-center">
{!isOwnProfile && (
<button
className="h-fit w-fit rounded-md bg-blue-500 p-1 hover:bg-blue-600"
onClick={claimProfile}
>
<HomeIcon title="Set as your Profile" width={24} height={24} />
</button>
)}
{!isOwnProfile && (
<>
{!settingsStore?.isFriend(playerId) && (
<button
className="rounded-md bg-blue-500 p-1 hover:opacity-80"
onClick={addFriend}
>
<UserIcon title="Add as Friend" width={24} height={24} />
</button>
)}
{settingsStore.isFriend(playerId) && (
<button
className="rounded-md bg-red-500 p-1 hover:opacity-80"
onClick={removeFriend}
>
<XMarkIcon title="Remove Friend" width={24} height={24} />
</button>
)}
</>
)}
</div>
</div> </div>
<div className="mt-1 flex w-full flex-col items-center gap-2 md:items-start">
{/* Name */}
<p className="text-2xl leading-none">{playerData.name}</p>
{/* Settings Buttons */} <div className="flex items-center gap-3 text-xl">
<div className="absolute right-3 top-20 flex flex-col justify-end gap-2 md:relative md:right-0 md:top-0 md:mt-2 md:flex-row md:justify-center"> {/* Global Rank */}
{!isOwnProfile && ( <div className="flex items-center gap-1 text-gray-300">
<button <GlobeAsiaAustraliaIcon width={32} height={32} />
className="h-fit w-fit rounded-md bg-blue-500 p-1 hover:bg-blue-600"
onClick={claimProfile}
>
<HomeIcon title="Set as your Profile" width={24} height={24} />
</button>
)}
{!isOwnProfile && ( <a
<> className="flex transform-gpu items-center gap-1 transition-all hover:text-blue-500"
{!settingsStore?.isFriend(playerId) && ( href={`/ranking/global/?page=${Math.round(
<button playerData.rank / 50,
className="rounded-md bg-blue-500 p-1 hover:opacity-80" )}`}
onClick={addFriend} >
> <p>#{formatNumber(playerData.rank)}</p>
<UserIcon title="Add as Friend" width={24} height={24} /> </a>
</button> </div>
)}
{settingsStore.isFriend(playerId) && ( {/* Country Rank */}
<button <div className="text-gray-300">
className="rounded-md bg-red-500 p-1 hover:opacity-80" <a
onClick={removeFriend} className="flex transform-gpu items-center gap-1 transition-all hover:text-blue-500"
> href={`/ranking/country/${playerData.country}?page=${Math.round(
<XMarkIcon title="Remove Friend" width={24} height={24} /> playerData.countryRank / 50,
</button> )}`}
)} >
</> <ReactCountryFlag
)} countryCode={playerData.country}
svg
className="!h-7 !w-7"
/>
<p>#{formatNumber(playerData.countryRank)}</p>
</a>
</div>
{/* PP */}
<div className="flex items-center text-gray-300">
<p>{formatNumber(playerData.pp)}pp</p>
</div>
</div>
{/* Labels */}
<div className="flex flex-wrap justify-center gap-2 md:justify-start">
<Label
title="Total play count"
className="bg-blue-500"
hoverValue="Total ranked song play count"
value={formatNumber(playerData.scoreStats.totalPlayCount)}
/>
<Label
title="Total score"
className="bg-blue-500"
hoverValue="Total score of all your plays"
value={formatNumber(playerData.scoreStats.totalScore)}
/>
<Label
title="Avg ranked acc"
className="bg-blue-500"
hoverValue="Average accuracy of all your ranked plays"
value={`${playerData.scoreStats.averageRankedAccuracy.toFixed(
2,
)}%`}
/>
{hasLocalScores && (
<>
<Label
title="Top PP"
className="bg-[#8992e8]"
hoverValue="Highest pp play"
value={`${formatNumber(
getHighestPpPlay(playerId)?.toFixed(2),
)}pp`}
/>
<Label
title="Avg PP"
className="bg-[#8992e8]"
hoverValue="Average amount of pp per play (best 20 scores)"
value={`${formatNumber(
getAveragePp(playerId)?.toFixed(2),
)}pp`}
/>
<Label
title="+ 1pp"
className="bg-[#8992e8]"
hoverValue="Amount of raw pp required to increase your global pp by 1pp"
value={`${formatNumber(
calcPpBoundary(playerId, 1)?.toFixed(2),
)}pp raw per global`}
/>
</>
)}
</div>
{/* Chart */}
<PlayerChart scoresaber={playerData} />
</div> </div>
</div> </div>
<div className="mt-1 flex w-full flex-col items-center gap-2 md:items-start"> </Card>
{/* Name */}
<p className="text-2xl leading-none">{playerData.name}</p>
<div className="flex items-center gap-3 text-xl">
{/* Global Rank */}
<div className="flex items-center gap-1 text-gray-300">
<GlobeAsiaAustraliaIcon width={32} height={32} />
<a
className="flex transform-gpu items-center gap-1 transition-all hover:text-blue-500"
href={`/ranking/global/${Math.ceil(playerData.rank / 50)}`}
>
<p>#{formatNumber(playerData.rank)}</p>
</a>
</div>
{/* Country Rank */}
<div className="text-gray-300">
<a
className="flex transform-gpu items-center gap-1 transition-all hover:text-blue-500"
href={`/ranking/country/${playerData.country}/${Math.ceil(
playerData.countryRank / 50,
)}`}
>
<ReactCountryFlag
countryCode={playerData.country}
svg
className="!h-7 !w-7"
/>
<p>#{formatNumber(playerData.countryRank)}</p>
</a>
</div>
{/* PP */}
<div className="flex items-center text-gray-300">
<p>{formatNumber(playerData.pp)}pp</p>
</div>
</div>
{/* Labels */}
<div className="flex flex-wrap justify-center gap-2 md:justify-start">
<Label
title="Total play count"
className="bg-blue-500"
hoverValue="Total ranked song play count"
value={formatNumber(playerData.scoreStats.totalPlayCount)}
/>
<Label
title="Total score"
className="bg-blue-500"
hoverValue="Total score of all your plays"
value={formatNumber(playerData.scoreStats.totalScore)}
/>
<Label
title="Avg ranked acc"
className="bg-blue-500"
hoverValue="Average accuracy of all your ranked plays"
value={`${playerData.scoreStats.averageRankedAccuracy.toFixed(2)}%`}
/>
{hasLocalScores && (
<>
<Label
title="Top PP"
className="bg-[#8992e8]"
hoverValue="Highest pp play"
value={`${formatNumber(
getHighestPpPlay(playerId)?.toFixed(2),
)}pp`}
/>
<Label
title="Avg PP"
className="bg-[#8992e8]"
hoverValue="Average amount of pp per play (best 20 scores)"
value={`${formatNumber(getAveragePp(playerId)?.toFixed(2))}pp`}
/>
<Label
title="+ 1pp"
className="bg-[#8992e8]"
hoverValue="Amount of raw pp required to increase your global pp by 1pp"
value={`${formatNumber(
calcPpBoundary(playerId, 1)?.toFixed(2),
)}pp raw per global`}
/>
</>
)}
</div>
{/* Chart */}
<PlayerChart scoresaber={playerData} />
</div>
</div>
); );
} }

@ -0,0 +1,109 @@
"use client";
import Card from "@/components/Card";
import Container from "@/components/Container";
import Spinner from "@/components/Spinner";
import Scores from "@/components/player/Scores";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { useSettingsStore } from "@/store/settingsStore";
import { SortType, SortTypes } from "@/types/SortTypes";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
import useStore from "@/utils/useStore";
import dynamic from "next/dynamic";
import { useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import PlayerInfo from "./PlayerInfo";
const Error = dynamic(() => import("@/components/Error"));
type PlayerInfo = {
loading: boolean;
player: ScoresaberPlayer | undefined;
};
type PlayerPageProps = {
id: string;
};
const DEFAULT_SORT_TYPE = SortTypes.top;
export default function PlayerPage({ id }: PlayerPageProps) {
const settingsStore = useStore(useSettingsStore, (store) => store);
const searchParams = useSearchParams();
const [mounted, setMounted] = useState(false);
const [error, setError] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [player, setPlayer] = useState<PlayerInfo>({
loading: true,
player: undefined,
});
let page;
const pageString = searchParams.get("page");
if (pageString == null) {
page = 1;
} else {
page = Number.parseInt(pageString) || 1;
}
let sortType: SortType;
const sortTypeString = searchParams.get("sort");
if (sortTypeString == null) {
sortType = settingsStore?.lastUsedSortType || DEFAULT_SORT_TYPE;
} else {
sortType = SortTypes[sortTypeString] || DEFAULT_SORT_TYPE;
}
useEffect(() => {
setMounted(true);
if (error || !player.loading) {
return;
}
if (mounted == true) {
return;
}
ScoreSaberAPI.fetchPlayerData(id).then((playerResponse) => {
if (!playerResponse) {
setError(true);
setErrorMessage("Failed to fetch player. Is the ID correct?");
setPlayer({ ...player, loading: false });
return;
}
setPlayer({ ...player, player: playerResponse, loading: false });
});
}, [error, mounted, id, player]);
if (player.loading || error || !player.player) {
return (
<main>
<Container>
<Card className="mt-2">
<div className="p-3 text-center">
<div role="status">
<div className="flex flex-col items-center justify-center gap-2">
{error && <Error errorMessage={errorMessage} />}
{!error && <Spinner />}
</div>
</div>
</div>
</Card>
</Container>
</main>
);
}
const playerData = player.player;
return (
<main>
<Container>
<PlayerInfo playerData={playerData} />
<Scores playerData={playerData} page={page} sortType={sortType} />
</Container>
</main>
);
}

@ -1,5 +1,3 @@
"use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player"; import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { useSettingsStore } from "@/store/settingsStore"; import { useSettingsStore } from "@/store/settingsStore";
import { formatNumber } from "@/utils/number"; import { formatNumber } from "@/utils/number";

@ -1,5 +1,3 @@
"use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player"; import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { useSettingsStore } from "@/store/settingsStore"; import { useSettingsStore } from "@/store/settingsStore";
import { formatNumber } from "@/utils/number"; import { formatNumber } from "@/utils/number";
@ -24,7 +22,7 @@ export default function PlayerRankingMobile({
return ( return (
<div> <div>
<div className="m-3 flex flex-col gap-2"> <div className="m-3 flex flex-col gap-2">
<div className="flex items-center gap-2"> <p className="flex items-center gap-2">
<p>#{formatNumber(player.rank)}</p> <p>#{formatNumber(player.rank)}</p>
<Avatar url={player.profilePicture} label="Avatar" size={24} /> <Avatar url={player.profilePicture} label="Avatar" size={24} />
{showCountryFlag && ( {showCountryFlag && (
@ -43,7 +41,7 @@ export default function PlayerRankingMobile({
> >
{player.name} {player.name}
</p> </p>
</div> </p>
<div className="flex flex-wrap justify-center gap-2"> <div className="flex flex-wrap justify-center gap-2">
<Label <Label
title="PP" title="PP"

@ -1,110 +1,173 @@
"use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player"; import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { ScoresaberPlayerScore } from "@/schemas/scoresaber/playerScore"; import { ScoresaberPlayerScore } from "@/schemas/scoresaber/playerScore";
import { useSettingsStore } from "@/store/settingsStore"; import { useSettingsStore } from "@/store/settingsStore";
import { SortType, SortTypes } from "@/types/SortTypes"; import { SortType, SortTypes } from "@/types/SortTypes";
import { ScoreSaberAPI } from "@/utils/scoresaber/api";
import useStore from "@/utils/useStore"; import useStore from "@/utils/useStore";
import dynamic from "next/dynamic";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import Card from "../Card"; import Card from "../Card";
import Error from "../Error";
import Pagination from "../Pagination"; import Pagination from "../Pagination";
import Score from "./Score"; import Score from "./Score";
type ScoresProps = { const Spinner = dynamic(() => import("@/components/Spinner"));
playerData: ScoresaberPlayer;
type PageInfo = {
loading: boolean;
page: number; page: number;
totalPages: number; totalPages: number;
sortType: SortType; sortType: SortType;
scores: ScoresaberPlayerScore[]; scores: ScoresaberPlayerScore[];
}; };
export default function Scores({ type ScoresProps = {
playerData, playerData: ScoresaberPlayer;
page, page: number;
totalPages, sortType: SortType;
sortType, };
scores,
}: ScoresProps) { export default function Scores({ playerData, page, sortType }: ScoresProps) {
const settingsStore = useStore(useSettingsStore, (store) => store); const settingsStore = useStore(useSettingsStore, (store) => store);
const playerId = playerData.id; const playerId = playerData.id;
const router = useRouter(); const router = useRouter();
const lastUsedSortType = settingsStore?.lastUsedSortType; const [mounted, setMounted] = useState(false);
if (lastUsedSortType && lastUsedSortType != sortType) { const [error, setError] = useState(false);
router.push( const [errorMessage, setErrorMessage] = useState("");
`/player/${playerId}/scoresaber/${lastUsedSortType.value}/${page}`,
{
scroll: false,
},
);
}
function setPage(page: number, sortTypee?: SortType) { const [scores, setScores] = useState<PageInfo>({
if (sortTypee) { loading: true,
if (sortTypee.value !== sortType.value) { page: page,
settingsStore?.setLastUsedSortType(sortTypee); totalPages: 1,
} sortType: sortType,
} scores: [],
router.push( });
`/player/${playerId}/scoresaber/${
sortTypee ? sortTypee.value : sortType.value const updateScoresPage = useCallback(
}/${page}`, (sortType: SortType, page: any) => {
{ ScoreSaberAPI.fetchScores(playerId, page, sortType.value, 10).then(
scroll: false, (scoresResponse) => {
}, if (!scoresResponse) {
setError(true);
setErrorMessage("No Scores");
setScores({ ...scores, loading: false });
return;
}
setScores({
...scores,
scores: scoresResponse.scores,
totalPages: scoresResponse.pageInfo.totalPages,
loading: false,
page: page,
sortType: sortType,
});
settingsStore?.setLastUsedSortType(sortType);
if (page > 1) {
router.push(
`/player/${playerId}?page=${page}&sort=${sortType.value}`,
{
scroll: false,
},
);
} else {
router.push(`/player/${playerId}?sort=${sortType.value}`, {
scroll: false,
});
}
console.log(`Switched page to ${page} with sort ${sortType.value}`);
},
);
},
[playerId, router, scores, settingsStore],
);
useEffect(() => {
if (mounted) return;
setMounted(true);
updateScoresPage(scores.sortType, scores.page);
}, [mounted, updateScoresPage, scores.sortType, scores.page]);
if (error) {
return (
<Card className="mt-2">
<div className="p-3 text-center">
<div role="status">
<div className="flex flex-col items-center justify-center gap-2">
{error && <Error errorMessage={errorMessage} />}
</div>
</div>
</div>
</Card>
); );
} }
return ( return (
<Card className="w-full items-center md:flex-col"> <Card className="mt-2 w-full items-center md:flex-col">
{/* Sort */} {/* Sort */}
<div className="w-full text-sm"> <div className="m-2 w-full text-sm">
<div className="flex justify-center gap-2"> <div className="flex justify-center gap-2">
{Object.values(SortTypes).map((sortTypee) => { {Object.values(SortTypes).map((sortType) => {
return ( return (
<button <button
key={sortType.value} key={sortType.value}
className={`flex transform-gpu flex-row items-center gap-1 rounded-md p-[0.35rem] transition-all hover:opacity-80 ${ className={`flex transform-gpu flex-row items-center gap-1 rounded-md p-[0.35rem] transition-all hover:opacity-80 ${
sortType.value === sortTypee.value scores.sortType.value === sortType.value
? "bg-blue-500" ? "bg-blue-500"
: "bg-gray-500" : "bg-gray-500"
}`} }`}
onClick={() => { onClick={() => {
setPage(1, sortTypee); updateScoresPage(sortType, 1);
}} }}
> >
{sortTypee.icon} {sortType.icon}
<p>{sortTypee.name}</p> <p>{sortType.name}</p>
</button> </button>
); );
})} })}
</div> </div>
</div> </div>
<div className="mt-4 grid grid-cols-1 divide-y divide-gray-500"> <div className="w-full p-1">
{scores.map((scoreData, id) => { {scores.loading ? (
const { score, leaderboard } = scoreData; <div className="flex justify-center">
<Spinner />
</div>
) : (
<div className="grid grid-cols-1 divide-y divide-gray-500">
{!scores.loading && scores.scores.length == 0 ? (
<p className="text-red-400">{errorMessage}</p>
) : (
scores.scores.map((scoreData, id) => {
const { score, leaderboard } = scoreData;
return ( return (
<Score <Score
key={id} key={id}
player={playerData} player={playerData}
score={score} score={score}
leaderboard={leaderboard} leaderboard={leaderboard}
/> />
); );
})} })
)}
</div>
)}
</div> </div>
{/* Pagination */} {/* Pagination */}
<div className="flex w-full flex-row justify-center rounded-md bg-gray-800 md:flex-col"> <div className="flex w-full flex-row justify-center rounded-md bg-gray-800 md:flex-col">
<div className="p-3"> <div className="p-3">
<Pagination <Pagination
currentPage={page} currentPage={scores.page}
totalPages={totalPages} totalPages={scores.totalPages}
onPageChange={(page) => { onPageChange={(page) => {
setPage(page); updateScoresPage(scores.sortType, page);
}} }}
/> />
</div> </div>

@ -1,90 +1,90 @@
"use client"; "use client";
import { ScoresaberPlayer } from "@/schemas/scoresaber/player"; import { ScoresaberPlayer } from "@/schemas/scoresaber/player";
import { formatNumber } from "@/utils/number"; import { formatNumber } from "@/utils/number";
import { ScoreSaberAPI } from "@/utils/scoresaber/api"; import { ScoreSaberAPI } from "@/utils/scoresaber/api";
import { MagnifyingGlassIcon } from "@heroicons/react/20/solid"; import { MagnifyingGlassIcon } from "@heroicons/react/20/solid";
import clsx from "clsx"; import clsx from "clsx";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Avatar from "../Avatar"; import Avatar from "../Avatar";
export default function SearchPlayer() { export default function SearchPlayer() {
const [search, setSearch] = useState(""); const [search, setSearch] = useState("");
const [players, setPlayers] = useState([] as ScoresaberPlayer[]); const [players, setPlayers] = useState([] as ScoresaberPlayer[]);
useEffect(() => { useEffect(() => {
// Don't search if the query is too short // Don't search if the query is too short
if (search.length < 4) { if (search.length < 4) {
setPlayers([]); // Clear players setPlayers([]); // Clear players
return; return;
} }
searchPlayer(search); searchPlayer(search);
}, [search]); }, [search]);
async function searchPlayer(search: string) { async function searchPlayer(search: string) {
// Check if the search is a profile link // Check if the search is a profile link
if (search.startsWith("https://scoresaber.com/u/")) { if (search.startsWith("https://scoresaber.com/u/")) {
const id = search.split("/").pop(); const id = search.split("/").pop();
if (id == undefined) return; if (id == undefined) return;
const player = await ScoreSaberAPI.fetchPlayerData(id); const player = await ScoreSaberAPI.fetchPlayerData(id);
if (player == undefined) return; if (player == undefined) return;
setPlayers([player]); setPlayers([player]);
} }
// Search by name // Search by name
const players = await ScoreSaberAPI.searchByName(search); const players = await ScoreSaberAPI.searchByName(search);
if (players == undefined) return; if (players == undefined) return;
setPlayers(players); setPlayers(players);
} }
function handleSubmit(e: React.FormEvent<HTMLFormElement>) { function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault(); e.preventDefault();
// Take the user to the first account // Take the user to the first account
if (players.length > 0) { if (players.length > 0) {
window.location.href = `/player/${players[0].id}/scoresaber/top/1`; window.location.href = `/player/${players[0].id}`;
} }
} }
return ( return (
<form className="mt-6 flex gap-2" onSubmit={handleSubmit}> <form className="mt-6 flex gap-2" onSubmit={handleSubmit}>
<input <input
className="min-w-[14rem] border-b bg-transparent text-xs outline-none" className="min-w-[14rem] border-b bg-transparent text-xs outline-none"
type="text" type="text"
placeholder="Enter a name or ScoreSaber profile..." placeholder="Enter a name or ScoreSaber profile..."
value={search} value={search}
onChange={(e) => setSearch(e.target.value)} onChange={(e) => setSearch(e.target.value)}
/> />
<button className="transform-gpu rounded-md bg-blue-600 p-1 transition-all hover:opacity-80"> <button className="transform-gpu rounded-md bg-blue-600 p-1 transition-all hover:opacity-80">
<MagnifyingGlassIcon className="font-black" width={18} height={18} /> <MagnifyingGlassIcon className="font-black" width={18} height={18} />
</button> </button>
<div <div
className={clsx( className={clsx(
"absolute z-20 mt-7 flex max-h-[400px] min-w-[14rem] flex-col divide-y overflow-y-auto rounded-md bg-gray-700 shadow-sm", "absolute z-20 mt-7 flex max-h-[400px] min-w-[14rem] flex-col divide-y overflow-y-auto rounded-md bg-gray-700 shadow-sm",
players.length > 0 ? "flex" : "hidden", players.length > 0 ? "flex" : "hidden",
)} )}
> >
{players.map((player: ScoresaberPlayer) => ( {players.map((player: ScoresaberPlayer) => (
<a <a
key={player.id} key={player.id}
className="flex min-w-[14rem] items-center gap-2 rounded-md p-2 transition-all hover:bg-gray-600" className="flex min-w-[14rem] items-center gap-2 rounded-md p-2 transition-all hover:bg-gray-600"
href={`/player/${player.id}/scoresaber/top/1`} href={`/player/${player.id}`}
> >
<Avatar label="Account" size={40} url={player.profilePicture} /> <Avatar label="Account" size={40} url={player.profilePicture} />
<div> <div>
<p className="text-xs text-gray-400"> <p className="text-xs text-gray-400">
#{formatNumber(player.rank)} #{formatNumber(player.rank)}
</p> </p>
<p className="text-sm">{player.name}</p> <p className="text-sm">{player.name}</p>
</div> </div>
</a> </a>
))} ))}
</div> </div>
</form> </form>
); );
} }

@ -22,7 +22,6 @@ export function middleware(request: NextRequest) {
if (pathname == "/ranking/global") { if (pathname == "/ranking/global") {
return NextResponse.redirect(new URL("/ranking/global/1", request.url)); return NextResponse.redirect(new URL("/ranking/global/1", request.url));
} }
const requestHeaders = new Headers(request.headers); const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-url", request.url); requestHeaders.set("x-url", request.url);
return NextResponse.next({ return NextResponse.next({