add bsr, map and yt buttons to scores
Some checks failed
Deploy SSR / deploy (push) Has been cancelled

This commit is contained in:
Lee
2024-09-11 23:10:16 +01:00
parent 74f595e11a
commit b5df147728
77 changed files with 899 additions and 657 deletions

View File

@ -1,7 +1,7 @@
import { scoresaberLeaderboard } from "@/app/common/leaderboard/impl/scoresaber";
import { ScoreSort } from "@/app/common/leaderboard/sort";
import { formatNumberWithCommas } from "@/app/common/number-utils";
import PlayerData from "@/app/components/player/player-data";
import { scoresaberFetcher } from "@/common/data-fetcher/impl/scoresaber";
import { ScoreSort } from "@/common/data-fetcher/sort";
import { formatNumberWithCommas } from "@/common/number-utils";
import PlayerData from "@/components/player/player-data";
import { format } from "@formkit/tempo";
import { Metadata } from "next";
import { redirect } from "next/navigation";
@ -14,7 +14,7 @@ type Props = {
export async function generateMetadata({ params: { slug } }: Props): Promise<Metadata> {
const id = slug[0]; // The players id
const player = await scoresaberLeaderboard.lookupPlayer(id, false);
const player = await scoresaberFetcher.lookupPlayer(id, false);
if (player === undefined) {
return {
title: `Unknown Player`,
@ -42,7 +42,7 @@ export default async function Search({ params: { slug } }: Props) {
const id = slug[0]; // The players id
const sort: ScoreSort = (slug[1] as ScoreSort) || "recent"; // The sorting method
const page = parseInt(slug[2]) || 1; // The page number
const player = await scoresaberLeaderboard.lookupPlayer(id, false);
const player = await scoresaberFetcher.lookupPlayer(id, false);
if (player == undefined) {
// Invalid player id

View File

@ -1,4 +1,4 @@
import SearchPlayer from "@/app/components/input/search-player";
import SearchPlayer from "@/components/input/search-player";
import { Metadata } from "next";
export const metadata: Metadata = {

View File

@ -1,67 +0,0 @@
import Dexie, { EntityTable } from "dexie";
import { setPlayerIdCookie } from "../website-utils";
import Settings from "./types/settings";
const SETTINGS_ID = "SSR"; // DO NOT CHANGE
export default class Database extends Dexie {
/**
* The settings for the website.
*/
settings!: EntityTable<Settings, "id">;
constructor() {
super("ScoreSaberReloaded");
// Stores
this.version(1).stores({
settings: "id",
});
// Mapped tables
this.settings.mapToClass(Settings);
// Populate default settings if the table is empty
this.on("populate", () => this.populateDefaults());
this.on("ready", async () => {
const settings = await this.getSettings();
// If the settings are not found, return
if (settings == undefined || settings.playerId == undefined) {
return;
}
setPlayerIdCookie(settings.playerId);
});
}
/**
* Populates the default settings
*/
async populateDefaults() {
await this.settings.add({
id: SETTINGS_ID, // Fixed ID for the single settings object
backgroundImage: "/assets/background.jpg",
});
}
/**
* Gets the settings from the database
*
* @returns the settings
*/
async getSettings(): Promise<Settings | undefined> {
return await this.settings.get(SETTINGS_ID);
}
/**
* Sets the settings in the database
*
* @param settings the settings to set
* @returns the settings
*/
async setSettings(settings: Settings) {
return await this.settings.update(SETTINGS_ID, settings);
}
}
export const db = new Database();

View File

@ -1,42 +0,0 @@
import { Entity } from "dexie";
import Database from "../database";
/**
* The website settings.
*/
export default class Settings extends Entity<Database> {
/**
* This is just so we can fetch the settings
*/
id!: string;
/**
* The ID of the tracked player
*/
playerId?: string;
/**
* The background image to use
*/
backgroundImage?: string;
/**
* Sets the players id
*
* @param id the new player id
*/
public setPlayerId(id: string) {
this.playerId = id;
this.db.setSettings(this);
}
/**
* Sets the background image
*
* @param image the new background image
*/
public setBackgroundImage(image: string) {
this.backgroundImage = image;
this.db.setSettings(this);
}
}

View File

@ -1,11 +0,0 @@
import { config } from "../../../config";
/**
* Proxies all non-localhost images to make them load faster.
*
* @param originalUrl the original image url
* @returns the new image url
*/
export function getImageUrl(originalUrl: string) {
return `${!config.siteUrl.includes("localhost") ? "https://img.fascinated.cc/upload/q_70/" : ""}${originalUrl}`;
}

View File

@ -1,75 +0,0 @@
import Leaderboard from "../leaderboard";
import { ScoreSort } from "../sort";
import ScoreSaberPlayer from "../types/scoresaber/scoresaber-player";
import ScoreSaberPlayerScoresPage from "../types/scoresaber/scoresaber-player-scores-page";
import { ScoreSaberPlayerSearch } from "../types/scoresaber/scoresaber-player-search";
const API_BASE = "https://scoresaber.com/api";
const SEARCH_PLAYERS_ENDPOINT = `${API_BASE}/players?search=:query`;
const LOOKUP_PLAYER_ENDPOINT = `${API_BASE}/player/:id/full`;
const LOOKUP_PLAYER_SCORES_ENDPOINT = `${API_BASE}/player/:id/scores?limit=:limit&sort=:sort&page=:page`;
class ScoreSaberLeaderboard extends Leaderboard {
constructor() {
super("ScoreSaber");
}
/**
* Gets the players that match the query.
*
* @param query the query to search for
* @param useProxy whether to use the proxy or not
* @returns the players that match the query, or undefined if no players were found
*/
async searchPlayers(query: string, useProxy = true): Promise<ScoreSaberPlayerSearch | undefined> {
this.log(`Searching for players matching "${query}"...`);
const results = await this.fetch<ScoreSaberPlayerSearch>(
useProxy,
SEARCH_PLAYERS_ENDPOINT.replace(":query", query)
);
if (results.players.length === 0) {
return undefined;
}
results.players.sort((a, b) => a.rank - b.rank);
return results;
}
/**
* Looks up a player by their ID.
*
* @param playerId the ID of the player to look up
* @param useProxy whether to use the proxy or not
* @returns the player that matches the ID, or undefined
*/
async lookupPlayer(playerId: string, useProxy = true): Promise<ScoreSaberPlayer | undefined> {
this.log(`Looking up player "${playerId}"...`);
return await this.fetch<ScoreSaberPlayer>(useProxy, LOOKUP_PLAYER_ENDPOINT.replace(":id", playerId));
}
/**
* Looks up a page of scores for a player
*
* @param playerId the ID of the player to look up
* @param sort the sort to use
* @param page the page to get scores for
* @param useProxy whether to use the proxy or not
* @returns the scores of the player, or undefined
*/
async lookupPlayerScores(
playerId: string,
sort: ScoreSort,
page: number,
useProxy = true
): Promise<ScoreSaberPlayerScoresPage | undefined> {
this.log(`Looking up scores for player "${playerId}", sort "${sort}", page "${page}"...`);
return await this.fetch<ScoreSaberPlayerScoresPage>(
useProxy,
LOOKUP_PLAYER_SCORES_ENDPOINT.replace(":id", playerId)
.replace(":limit", 8 + "")
.replace(":sort", sort)
.replace(":page", page.toString())
);
}
}
export const scoresaberLeaderboard = new ScoreSaberLeaderboard();

View File

@ -1,54 +0,0 @@
import ky from "ky";
export default class Leaderboard {
/**
* The name of the leaderboard.
*/
private name: string;
constructor(name: string) {
this.name = name;
}
/**
* Logs a message to the console.
*
* @param data the data to log
*/
public log(data: unknown) {
console.log(`[${this.name}]: ${data}`);
}
/**
* Builds a request url.
*
* @param useProxy whether to use proxy or not
* @param url the url to fetch
* @returns the request url
*/
private buildRequestUrl(useProxy: boolean, url: string): string {
return (useProxy ? "https://proxy.fascinated.cc/" : "") + url;
}
/**
* Fetches data from the given url.
*
* @param useProxy whether to use proxy or not
* @param url the url to fetch
* @returns the fetched data
*/
public async fetch<T>(useProxy: boolean, url: string): Promise<T> {
try {
return await ky
.get<T>(this.buildRequestUrl(useProxy, url), {
next: {
revalidate: 60, // 1 minute
},
})
.json();
} catch (error) {
console.error(error);
throw error;
}
}
}

View File

@ -1,4 +0,0 @@
export enum ScoreSort {
top = "top",
recent = "recent",
}

View File

@ -1,11 +0,0 @@
export interface ScoreSaberBadge {
/**
* The description of the badge.
*/
description: string;
/**
* The image of the badge.
*/
image: string;
}

View File

@ -1,6 +0,0 @@
export default interface ScoreSaberDifficulty {
leaderboardId: number;
difficulty: number;
gameMode: string;
difficultyRaw: string;
}

View File

@ -1,8 +0,0 @@
export default interface ScoreSaberLeaderboardPlayerInfo {
id: string;
name: string;
profilePicture: string;
country: string;
permissions: number;
role: string;
}

View File

@ -1,26 +0,0 @@
import ScoreSaberDifficulty from "./scoresaber-difficulty";
export default interface ScoreSaberLeaderboard {
id: number;
songHash: string;
songName: string;
songSubName: string;
songAuthorName: string;
levelAuthorName: string;
difficulty: ScoreSaberDifficulty;
maxScore: number;
createdDate: string;
rankedDate: string;
qualifiedDate: string;
lovedDate: string;
ranked: boolean;
qualified: boolean;
loved: boolean;
maxPP: number;
stars: number;
positiveModifiers: boolean;
plays: boolean;
dailyPlays: boolean;
coverImage: string;
difficulties: ScoreSaberDifficulty[];
}

View File

@ -1,16 +0,0 @@
export default interface ScoreSaberMetadata {
/**
* The total amount of returned results.
*/
total: number;
/**
* The current page
*/
page: number;
/**
* The amount of results per page
*/
itemsPerPage: number;
}

View File

@ -1,14 +0,0 @@
import ScoreSaberLeaderboard from "./scoresaber-leaderboard";
import ScoreSaberScore from "./scoresaber-score";
export default interface ScoreSaberPlayerScore {
/**
* The score of the player score.
*/
score: ScoreSaberScore;
/**
* The leaderboard the score was set on.
*/
leaderboard: ScoreSaberLeaderboard;
}

View File

@ -1,14 +0,0 @@
import ScoreSaberMetadata from "./scoresaber-metadata";
import ScoreSaberPlayerScore from "./scoresaber-player-score";
export default interface ScoreSaberPlayerScoresPage {
/**
* The scores on this page.
*/
playerScores: ScoreSaberPlayerScore[];
/**
* The metadata for the page.
*/
metadata: ScoreSaberMetadata;
}

View File

@ -1,8 +0,0 @@
import ScoreSaberPlayer from "./scoresaber-player";
export interface ScoreSaberPlayerSearch {
/**
* The players that were found
*/
players: ScoreSaberPlayer[];
}

View File

@ -1,84 +0,0 @@
import { ScoreSaberBadge } from "./scoresaber-badge";
import ScoreSaberScoreStats from "./scoresaber-score-stats";
export default interface ScoreSaberPlayer {
/**
* The ID of the player.
*/
id: string;
/**
* The name of the player.
*/
name: string;
/**
* The profile picture of the player.
*/
profilePicture: string;
/**
* The bio of the player.
*/
bio: string | null;
/**
* The country of the player.
*/
country: string;
/**
* The amount of pp the player has.
*/
pp: number;
/**
* The rank of the player.
*/
rank: number;
/**
* The rank the player has in their country.
*/
countryRank: number;
/**
* The role of the player.
*/
role: string | null;
/**
* The badges the player has.
*/
badges: ScoreSaberBadge[] | null;
/**
* The previous 50 days of rank history.
*/
histories: string;
/**
* The score stats of the player.
*/
scoreStats: ScoreSaberScoreStats;
/**
* The permissions of the player. (bitwise)
*/
permissions: number;
/**
* Whether the player is banned or not.
*/
banned: boolean;
/**
* Whether the player is inactive or not.
*/
inactive: boolean;
/**
* The date the player joined ScoreSaber.
*/
firstSeen: string;
}

View File

@ -1,31 +0,0 @@
export default interface ScoreSaberScoreStats {
/**
* The total amount of score accumulated over all scores.
*/
totalScore: number;
/**
* The total amount of ranked score accumulated over all scores.
*/
totalRankedScore: number;
/**
* The average ranked accuracy for all ranked scores.
*/
averageRankedAccuracy: number;
/**
* The total amount of scores set.
*/
totalPlayCount: number;
/**
* The total amount of ranked score set.
*/
rankedPlayCount: number;
/**
* The amount of times their replays were watched.
*/
replaysWatched: number;
}

View File

@ -1,25 +0,0 @@
import ScoreSaberLeaderboard from "./scoresaber-leaderboard";
import ScoreSaberLeaderboardPlayerInfo from "./scoresaber-leaderboard-player-info";
export default interface ScoreSaberScore {
id: string;
leaderboardPlayerInfo: ScoreSaberLeaderboardPlayerInfo;
rank: number;
baseScore: number;
modifiedScore: number;
pp: number;
weight: number;
modifiers: string;
multiplier: number;
badCuts: number;
missedNotes: number;
maxCombo: number;
fullCombo: boolean;
hmd: number;
hasReplay: boolean;
timeSet: string;
deviceHmd: string;
deviceControllerLeft: string;
deviceControllerRight: string;
leaderboard: ScoreSaberLeaderboard;
}

View File

@ -1,9 +0,0 @@
/**
* Formats a number without trailing zeros.
*
* @param num the number to format
* @returns the formatted number
*/
export function formatNumberWithCommas(num: number) {
return num.toLocaleString();
}

View File

@ -1,9 +0,0 @@
/**
* Capitalizes the first letter of a string.
*
* @param str the string to capitalize
* @returns the capitalized string
*/
export function capitalizeFirstLetter(str: string) {
return str.charAt(0).toUpperCase() + str.slice(1);
}

View File

@ -1,26 +0,0 @@
/**
* This function returns the time ago of the input date
*
* @param input Date | number
* @returns the format of the time ago
*/
export function timeAgo(input: Date | number) {
const date = input instanceof Date ? input : new Date(input);
const formatter = new Intl.RelativeTimeFormat("en");
const ranges: { [key: string]: number } = {
year: 3600 * 24 * 365,
month: 3600 * 24 * 30,
week: 3600 * 24 * 7,
day: 3600 * 24,
hour: 3600,
minute: 60,
second: 1,
};
const secondsElapsed = (date.getTime() - Date.now()) / 1000;
for (const key in ranges) {
if (ranges[key] < Math.abs(secondsElapsed)) {
const delta = secondsElapsed / ranges[key];
return formatter.format(Math.round(delta), key as Intl.RelativeTimeFormatUnit);
}
}
}

View File

@ -1,6 +0,0 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

View File

@ -1,8 +0,0 @@
/**
* Sets the player id cookie
*
* @param playerId the player id to set
*/
export function setPlayerIdCookie(playerId: string) {
document.cookie = `playerId=${playerId}`;
}

View File

@ -1,37 +0,0 @@
"use client";
import { useLiveQuery } from "dexie-react-hooks";
import { config } from "../../../config";
import { getImageUrl } from "../common/image-utils";
import useDatabase from "../hooks/use-database";
export default function BackgroundImage() {
const database = useDatabase();
const settings = useLiveQuery(() => database.getSettings());
if (settings?.backgroundImage == undefined || settings?.backgroundImage == "") {
return null; // Don't render anything if the background image is not set
}
let backgroundImage = settings.backgroundImage;
let prependWebsiteUrl = false;
// Remove the prepending slash
if (backgroundImage.startsWith("/")) {
prependWebsiteUrl = true;
backgroundImage = backgroundImage.substring(1);
}
if (prependWebsiteUrl) {
backgroundImage = config.siteUrl + "/" + backgroundImage;
}
return (
// eslint-disable-next-line @next/next/no-img-element
<img
src={getImageUrl(backgroundImage)}
alt="Background image"
fetchPriority="high"
className={`fixed -z-50 object-cover w-screen h-screen blur-sm brightness-[33%] pointer-events-none select-none`}
/>
);
}

View File

@ -1,10 +0,0 @@
import clsx, { ClassValue } from "clsx";
type Props = {
children: React.ReactNode;
className?: ClassValue;
};
export default function Card({ children, className }: Props) {
return <div className={clsx("flex flex-col bg-secondary/90 p-3 rounded-md", className)}>{children}</div>;
}

View File

@ -1,20 +0,0 @@
export const CustomizedAxisTick = ({
x,
y,
payload,
rotateAngle = -45,
}: {
x?: number;
y?: number;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
payload?: any;
rotateAngle?: number;
}) => {
return (
<g transform={`translate(${x},${y})`}>
<text x={0} y={0} dy={16} textAnchor="end" fill="#666" transform={`rotate(${rotateAngle})`}>
{payload.value}
</text>
</g>
);
};

View File

@ -1,11 +0,0 @@
type Props = {
country: string;
size?: number;
};
export default function CountryFlag({ country, size = 24 }: Props) {
return (
// eslint-disable-next-line @next/next/no-img-element
<img alt="Player Country" src={`/assets/flags/${country}.png`} width={size * 2} height={size} />
);
}

View File

@ -1,118 +0,0 @@
import { useEffect, useState } from "react";
import {
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
Pagination as ShadCnPagination,
} from "../ui/pagination";
type Props = {
/**
* If true, the pagination will be rendered as a mobile-friendly pagination.
*/
mobilePagination: boolean;
/**
* The current page.
*/
page: number;
/**
* The total number of pages.
*/
totalPages: number;
/**
* Callback function that is called when the user clicks on a page number.
*/
onPageChange: (page: number) => void;
};
export default function Pagination({ mobilePagination, page, totalPages, onPageChange }: Props) {
totalPages = Math.round(totalPages);
const [currentPage, setCurrentPage] = useState(page);
useEffect(() => {
setCurrentPage(page);
}, [page]);
const handlePageChange = (newPage: number) => {
if (newPage < 1 || newPage > totalPages || newPage == currentPage) {
return;
}
setCurrentPage(newPage);
onPageChange(newPage);
};
const renderPageNumbers = () => {
const pageNumbers = [];
const maxPagesToShow = mobilePagination ? 3 : 4;
let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
const endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
if (endPage - startPage < maxPagesToShow - 1) {
startPage = Math.max(1, endPage - maxPagesToShow + 1);
}
// Show "Jump to Start" with Ellipsis if currentPage is greater than 3 in desktop view
if (startPage > 1 && !mobilePagination) {
pageNumbers.push(
<>
<PaginationItem key="start">
<PaginationLink onClick={() => handlePageChange(1)}>1</PaginationLink>
</PaginationItem>
<PaginationItem key="ellipsis-start">
<PaginationEllipsis />
</PaginationItem>
</>
);
}
// Generate page numbers between startPage and endPage for desktop view
for (let i = startPage; i <= endPage; i++) {
pageNumbers.push(
<PaginationItem key={i}>
<PaginationLink isActive={i === currentPage} onClick={() => handlePageChange(i)}>
{i}
</PaginationLink>
</PaginationItem>
);
}
return pageNumbers;
};
return (
<ShadCnPagination className="select-none">
<PaginationContent>
{/* Previous button for mobile and desktop */}
<PaginationItem>
<PaginationPrevious onClick={() => handlePageChange(currentPage - 1)} />
</PaginationItem>
{renderPageNumbers()}
{/* For desktop, show ellipsis and link to the last page */}
{!mobilePagination && currentPage < totalPages && (
<>
<PaginationItem key="ellipsis-end">
<PaginationEllipsis />
</PaginationItem>
<PaginationItem key="end">
<PaginationLink onClick={() => handlePageChange(totalPages)}>{totalPages}</PaginationLink>
</PaginationItem>
</>
)}
{/* Next button for mobile and desktop */}
<PaginationItem>
<PaginationNext onClick={() => handlePageChange(currentPage + 1)} />
</PaginationItem>
</PaginationContent>
</ShadCnPagination>
);
}

View File

@ -1,92 +0,0 @@
"use client";
import { scoresaberLeaderboard } from "@/app/common/leaderboard/impl/scoresaber";
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player";
import { formatNumberWithCommas } from "@/app/common/number-utils";
import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar";
import { Button } from "../ui/button";
import { Form, FormControl, FormField, FormItem, FormLabel } from "../ui/form";
import { Input } from "../ui/input";
import { ScrollArea } from "../ui/scroll-area";
const formSchema = z.object({
username: z.string().min(2).max(50),
});
export default function SearchPlayer() {
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
username: "",
},
});
const [results, setResults] = useState<ScoreSaberPlayer[] | undefined>();
const [loading, setLoading] = useState(false);
async function onSubmit({ username }: z.infer<typeof formSchema>) {
setLoading(true);
setResults(undefined); // Reset results
const results = await scoresaberLeaderboard.searchPlayers(username);
setResults(results?.players);
setLoading(false);
}
return (
<div className="flex flex-col gap-3">
{/* Search */}
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex items-end gap-2">
<FormField
control={form.control}
name="username"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input className="w-full sm:w-72 text-sm" placeholder="Query..." {...field} />
</FormControl>
</FormItem>
)}
/>
<Button type="submit">Search</Button>
</form>
</Form>
{/* Results */}
{loading == true && (
<div className="flex items-center justify-center">
<p>Loading...</p>
</div>
)}
{results !== undefined && (
<ScrollArea>
<div className="flex flex-col gap-1 max-h-60">
{results?.map((player) => {
return (
<Link
href={`/player/${player.id}`}
key={player.id}
className="bg-secondary p-2 rounded-md flex gap-2 items-center hover:brightness-75 transition-all transform-gpu"
>
<Avatar>
<AvatarImage src={player.profilePicture} />
<AvatarFallback>{player.name.at(0)}</AvatarFallback>
</Avatar>
<div>
<p>{player.name}</p>
<p className="text-gray-400 text-sm">#{formatNumberWithCommas(player.rank)}</p>
</div>
</Link>
);
})}
</div>
</ScrollArea>
)}
</div>
);
}

View File

@ -1,30 +0,0 @@
"use client";
import { createContext, useEffect, useState } from "react";
import Database, { db } from "../../common/database/database";
import FullscreenLoader from "./fullscreen-loader";
/**
* The context for the database. This is used to access the database from within the app.
*/
export const DatabaseContext = createContext<Database | undefined>(undefined);
type Props = {
children: React.ReactNode;
};
export default function DatabaseLoader({ children }: Props) {
const [database, setDatabase] = useState<Database | undefined>(undefined);
useEffect(() => {
const before = performance.now();
setDatabase(db);
console.log(`Loaded database in ${performance.now() - before}ms`);
}, []);
return (
<DatabaseContext.Provider value={database}>
{database == undefined ? <FullscreenLoader reason="Loading database..." /> : children}
</DatabaseContext.Provider>
);
}

View File

@ -1,19 +0,0 @@
import ScoreSaberLogo from "../logos/scoresaber-logo";
type Props = {
reason: string;
};
export default function FullscreenLoader({ reason }: Props) {
return (
<div className="absolute w-screen h-screen bg-background brightness-75 flex flex-col gap-6 items-center justify-center">
<div className="flex flex-col items-center justify-center">
<p className="text-white text-xl font-bold">ScoreSaber Reloaded</p>
<p className="text-gray-300 text-md">{reason}</p>
</div>
<div className="animate-spin">
<ScoreSaberLogo />
</div>
</div>
);
}

View File

@ -1,7 +0,0 @@
import Image from "next/image";
export default function ScoreSaberLogo() {
return (
<Image width={32} height={32} unoptimized src={"/assets/logos/scoresaber.png"} alt={"ScoreSaber Logo"}></Image>
);
}

View File

@ -1,11 +0,0 @@
type Props = {
children: React.ReactNode;
};
export default function NavbarButton({ children }: Props) {
return (
<div className="px-2 gap-2 rounded-md hover:bg-blue-500 transform-gpu transition-all h-full flex items-center">
{children}
</div>
);
}

View File

@ -1,57 +0,0 @@
import { HomeIcon } from "@heroicons/react/24/solid";
import { MagnifyingGlassIcon } from "@radix-ui/react-icons";
import Link from "next/link";
import React from "react";
import NavbarButton from "./navbar-button";
import ProfileButton from "./profile-button";
type NavbarItem = {
name: string;
link: string;
icon: React.ReactNode;
};
const items: NavbarItem[] = [
{
name: "Home",
link: "/",
icon: <HomeIcon className="h-5 w-5" />, // Add your home icon here
},
{
name: "Search",
link: "/search",
icon: <MagnifyingGlassIcon className="h-5 w-5" />, // Add your search icon here
},
];
// Helper function to render each navbar item
const renderNavbarItem = (item: NavbarItem) => (
<div className="flex items-center">
{item.icon && <div className="mr-2">{item.icon}</div>}
<div>{item.name}</div>
</div>
);
export default function Navbar() {
return (
<div className="w-full py-2">
<div className="h-10 rounded-md items-center flex justify-between bg-secondary/90">
{/* Left-aligned items */}
<div className="flex items-center h-full">
<ProfileButton />
{items.slice(0, -1).map((item, index) => (
<NavbarButton key={index}>
<Link href={item.link}>{renderNavbarItem(item)}</Link>
</NavbarButton>
))}
</div>
{/* Right-aligned item */}
<NavbarButton>
<Link href={items[items.length - 1].link}>{renderNavbarItem(items[items.length - 1])}</Link>
</NavbarButton>
</div>
</div>
);
}

View File

@ -1,31 +0,0 @@
"use client";
import useDatabase from "@/app/hooks/use-database";
import { useLiveQuery } from "dexie-react-hooks";
import Link from "next/link";
import { Avatar, AvatarImage } from "../ui/avatar";
import NavbarButton from "./navbar-button";
export default function ProfileButton() {
const database = useDatabase();
const settings = useLiveQuery(() => database.getSettings());
if (settings == undefined) {
return; // Settings hasn't loaded yet
}
if (settings.playerId == null) {
return; // No player profile claimed
}
return (
<NavbarButton>
<Link href={`/player/${settings.playerId}`} className="flex items-center gap-2">
<Avatar className="w-6 h-6">
<AvatarImage src={`https://cdn.scoresaber.com/avatars/${settings.playerId}.jpg`} />
</Avatar>
<p>You</p>
</Link>
</NavbarButton>
);
}

View File

@ -1,53 +0,0 @@
"use client";
import { CheckIcon } from "@heroicons/react/24/solid";
import { useLiveQuery } from "dexie-react-hooks";
import { setPlayerIdCookie } from "../../common/website-utils";
import useDatabase from "../../hooks/use-database";
import { useToast } from "../../hooks/use-toast";
import { Button } from "../ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
type Props = {
/**
* The ID of the players profile to claim.
*/
playerId: string;
};
export default function ClaimProfile({ playerId }: Props) {
const database = useDatabase();
const { toast } = useToast();
const settings = useLiveQuery(() => database.getSettings());
/**
* Claims the profile.
*/
async function claimProfile() {
const settings = await database.getSettings();
settings?.setPlayerId(playerId);
setPlayerIdCookie(playerId);
toast({
title: "Profile Claimed",
description: "You have claimed this profile.",
});
}
if (settings?.playerId == playerId || settings == undefined) {
return null; // Don't show the claim button if it's the same user.
}
return (
<Tooltip>
<TooltipTrigger asChild>
<Button variant={"outline"} onClick={claimProfile}>
<CheckIcon className="size-6 text-green-500" />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>Set as your profile</p>
</TooltipContent>
</Tooltip>
);
}

View File

@ -1,13 +0,0 @@
type Props = {
icon?: React.ReactNode;
children: React.ReactNode;
};
export default function PlayerDataPoint({ icon, children }: Props) {
return (
<div className="flex gap-1 items-center">
{icon}
{children}
</div>
);
}

View File

@ -1,38 +0,0 @@
"use client";
import { scoresaberLeaderboard } from "@/app/common/leaderboard/impl/scoresaber";
import { ScoreSort } from "@/app/common/leaderboard/sort";
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player";
import { useQuery } from "@tanstack/react-query";
import PlayerHeader from "./player-header";
import PlayerRankChart from "./player-rank-chart";
import PlayerScores from "./player-scores";
const REFRESH_INTERVAL = 5 * 60 * 1000; // 5 minutes
type Props = {
initalPlayerData: ScoreSaberPlayer;
sort: ScoreSort;
page: number;
};
export default function PlayerData({ initalPlayerData, sort, page }: Props) {
let player = initalPlayerData;
const { data, isLoading, isError } = useQuery({
queryKey: ["player", player.id],
queryFn: () => scoresaberLeaderboard.lookupPlayer(player.id),
refetchInterval: REFRESH_INTERVAL,
});
if (data && (!isLoading || !isError)) {
player = data;
}
return (
<div className="flex flex-col gap-2">
<PlayerHeader player={player} />
<PlayerRankChart player={player} />
<PlayerScores player={player} sort={sort} page={page} />
</div>
);
}

View File

@ -1,63 +0,0 @@
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player";
import { formatNumberWithCommas } from "@/app/common/number-utils";
import { GlobeAmericasIcon } from "@heroicons/react/24/solid";
import Card from "../card";
import CountryFlag from "../country-flag";
import { Avatar, AvatarImage } from "../ui/avatar";
import ClaimProfile from "./claim-profile";
import PlayerDataPoint from "./player-data-point";
const playerSubNames = [
{
icon: () => {
return <GlobeAmericasIcon className="h-5 w-5" />;
},
render: (player: ScoreSaberPlayer) => {
return <p>#{formatNumberWithCommas(player.rank)}</p>;
},
},
{
icon: (player: ScoreSaberPlayer) => {
return <CountryFlag country={player.country.toLowerCase()} size={15} />;
},
render: (player: ScoreSaberPlayer) => {
return <p>#{formatNumberWithCommas(player.countryRank)}</p>;
},
},
{
render: (player: ScoreSaberPlayer) => {
return <p className="text-pp">{formatNumberWithCommas(player.pp)}pp</p>;
},
},
];
type Props = {
player: ScoreSaberPlayer;
};
export default function PlayerHeader({ player }: Props) {
return (
<Card>
<div className="flex gap-3 flex-col items-center text-center sm:flex-row sm:items-start sm:text-start relative select-none">
<Avatar className="w-32 h-32 pointer-events-none">
<AvatarImage fetchPriority="high" src={player.profilePicture} />
</Avatar>
<div>
<p className="font-bold text-2xl">{player.name}</p>
<div className="flex gap-2">
{playerSubNames.map((subName, index) => {
return (
<PlayerDataPoint icon={subName.icon && subName.icon(player)} key={index}>
{subName.render(player)}
</PlayerDataPoint>
);
})}
</div>
<div className="absolute top-0 right-0">
<ClaimProfile playerId={player.id} />
</div>
</div>
</div>
</Card>
);
}

View File

@ -1,112 +0,0 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player";
import { formatNumberWithCommas } from "@/app/common/number-utils";
import { CategoryScale, Chart, Legend, LinearScale, LineElement, PointElement, Title, Tooltip } from "chart.js";
import { Line } from "react-chartjs-2";
import Card from "../card";
Chart.register(LinearScale, CategoryScale, PointElement, LineElement, Title, Tooltip, Legend);
export const options: any = {
maintainAspectRatio: false,
aspectRatio: 1,
interaction: {
mode: "index",
intersect: false,
},
scales: {
y: {
ticks: {
autoSkip: true,
maxTicksLimit: 8,
stepSize: 1,
},
grid: {
// gray grid lines
color: "#252525",
},
reverse: true,
},
x: {
ticks: {
autoSkip: true,
},
grid: {
// gray grid lines
color: "#252525",
},
},
},
elements: {
point: {
radius: 0,
},
},
plugins: {
legend: {
position: "top" as const,
labels: {
color: "white",
},
},
title: {
display: false,
},
tooltip: {
callbacks: {
label(context: any) {
switch (context.dataset.label) {
case "Rank": {
return `Rank #${formatNumberWithCommas(Number(context.parsed.y))}`;
}
}
},
},
},
},
};
type Props = {
player: ScoreSaberPlayer;
};
export default function PlayerRankChart({ player }: Props) {
const playerRankHistory = player.histories.split(",").map((value) => {
return parseInt(value);
});
playerRankHistory.push(player.rank);
const labels = [];
for (let i = playerRankHistory.length; i > 0; i--) {
let label = `${i} days ago`;
if (i === 1) {
label = "now";
}
if (i === 2) {
label = "yesterday";
}
labels.push(label);
}
const data = {
labels,
datasets: [
{
lineTension: 0.5,
data: playerRankHistory,
label: "Rank",
borderColor: "#c084fc",
fill: false,
color: "#fff",
},
],
};
return (
<Card className="h-96">
<Line options={options} data={data} />
</Card>
);
}

View File

@ -1,98 +0,0 @@
"use client";
import { scoresaberLeaderboard } from "@/app/common/leaderboard/impl/scoresaber";
import { ScoreSort } from "@/app/common/leaderboard/sort";
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player";
import ScoreSaberPlayerScoresPage from "@/app/common/leaderboard/types/scoresaber/scoresaber-player-scores-page";
import { capitalizeFirstLetter } from "@/app/common/string-utils";
import useWindowDimensions from "@/app/hooks/use-window-dimensions";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import Card from "../card";
import Pagination from "../input/pagination";
import { Button } from "../ui/button";
import Score from "./score";
type Props = {
player: ScoreSaberPlayer;
sort: ScoreSort;
page: number;
};
export default function PlayerScores({ player, sort, page }: Props) {
const { width } = useWindowDimensions();
const [currentSort, setCurrentSort] = useState(sort);
const [currentPage, setCurrentPage] = useState(page);
const [previousScores, setPreviousScores] = useState<ScoreSaberPlayerScoresPage | undefined>();
const { data, isError, refetch } = useQuery({
queryKey: ["playerScores", player.id, currentSort, currentPage],
queryFn: () => scoresaberLeaderboard.lookupPlayerScores(player.id, currentSort, currentPage),
});
useEffect(() => {
if (data) {
setPreviousScores(data);
}
}, [data]);
useEffect(() => {
// Update URL and refetch data when currentSort or currentPage changes
const newUrl = `/player/${player.id}/${currentSort}/${currentPage}`;
window.history.replaceState({ ...window.history.state, as: newUrl, url: newUrl }, "", newUrl);
refetch();
}, [currentSort, currentPage, refetch, player.id]);
/**
* Updates the current sort and resets the page to 1
*/
function handleSortChange(newSort: ScoreSort) {
if (newSort !== currentSort) {
setCurrentSort(newSort);
setCurrentPage(1); // Reset the page
}
}
if (previousScores === undefined) {
return null;
}
if (isError) {
return (
<Card className="gap-2">
<p>Oopsies!</p>
</Card>
);
}
return (
<Card className="flex gap-4">
<div className="flex items-center flex-row w-full gap-2 justify-center">
{Object.keys(ScoreSort).map((sort, index) => (
<Button
variant={sort == currentSort ? "default" : "outline"}
key={index}
onClick={() => handleSortChange(sort as ScoreSort)}
>
{capitalizeFirstLetter(sort)}
</Button>
))}
</div>
<div className="grid min-w-full grid-cols-1 divide-y divide-border">
{previousScores.playerScores.map((playerScore, index) => (
<Score key={index} playerScore={playerScore} />
))}
</div>
<Pagination
mobilePagination={width < 768}
page={currentPage}
totalPages={Math.ceil(previousScores.metadata.total / previousScores.metadata.itemsPerPage)}
onPageChange={(newPage) => {
setCurrentPage(newPage);
}}
/>
</Card>
);
}

View File

@ -1,45 +0,0 @@
import ScoreSaberPlayerScore from "@/app/common/leaderboard/types/scoresaber/scoresaber-player-score";
import { timeAgo } from "@/app/common/time-utils";
import { GlobeAmericasIcon } from "@heroicons/react/24/solid";
import Image from "next/image";
type Props = {
/**
* The score to display.
*/
playerScore: ScoreSaberPlayerScore;
};
export default function Score({ playerScore }: Props) {
const { score, leaderboard } = playerScore;
return (
<div className="grid gap-2 md:gap-0 grid-cols-1 pb-2 pt-2 first:pt-0 last:pb-0 grid-cols-[20px 1fr] md:grid-cols-[0.85fr_6fr_1.3fr]">
<div className="flex w-full flex-row justify-between items-center md:w-[125px] md:justify-center md:flex-col">
<div className="flex gap-1 items-center">
<GlobeAmericasIcon className="w-5 h-5" />
<p className="text-pp">#{score.rank}</p>
</div>
<p className="text-sm">{timeAgo(new Date(score.timeSet))}</p>
</div>
<div className="flex gap-3">
<Image
unoptimized
src={leaderboard.coverImage}
width={64}
height={64}
alt="Song Artwork"
className="rounded-md"
/>
<div className="flex">
<div className="flex flex-col">
<p>{leaderboard.songName}</p>
<p className="text-sm">{leaderboard.songAuthorName}</p>
<p className="text-sm">{leaderboard.levelAuthorName}</p>
</div>
</div>
</div>
<div className="flex justify-end">stats stuff</div>
</div>
);
}

View File

@ -1,13 +0,0 @@
"use client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
type Props = {
children: React.ReactNode;
};
const queryClient = new QueryClient();
export function QueryProvider({ children }: Props) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
}

View File

@ -1,8 +0,0 @@
"use client";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { type ThemeProviderProps } from "next-themes/dist/types";
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

View File

@ -1,50 +0,0 @@
"use client"
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/app/common/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
"relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
className
)}
{...props}
/>
))
Avatar.displayName = AvatarPrimitive.Root.displayName
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
{...props}
/>
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
"flex h-full w-full items-center justify-center rounded-full bg-muted",
className
)}
{...props}
/>
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName
export { Avatar, AvatarImage, AvatarFallback }

View File

@ -1,57 +0,0 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/app/common/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

View File

@ -1,76 +0,0 @@
import * as React from "react"
import { cn } from "@/app/common/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

View File

@ -1,178 +0,0 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
ControllerProps,
FieldPath,
FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form"
import { cn } from "@/app/common/utils"
import { Label } from "@/app/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-[0.8rem] text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message) : children
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-[0.8rem] font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

View File

@ -1,25 +0,0 @@
import * as React from "react"
import { cn } from "@/app/common/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View File

@ -1,26 +0,0 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/app/common/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@ -1,121 +0,0 @@
import * as React from "react"
import {
ChevronLeftIcon,
ChevronRightIcon,
DotsHorizontalIcon,
} from "@radix-ui/react-icons"
import { cn } from "@/app/common/utils"
import { ButtonProps, buttonVariants } from "@/app/components/ui/button"
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
<nav
role="navigation"
aria-label="pagination"
className={cn("mx-auto flex w-full justify-center", className)}
{...props}
/>
)
Pagination.displayName = "Pagination"
const PaginationContent = React.forwardRef<
HTMLUListElement,
React.ComponentProps<"ul">
>(({ className, ...props }, ref) => (
<ul
ref={ref}
className={cn("flex flex-row items-center gap-1", className)}
{...props}
/>
))
PaginationContent.displayName = "PaginationContent"
const PaginationItem = React.forwardRef<
HTMLLIElement,
React.ComponentProps<"li">
>(({ className, ...props }, ref) => (
<li ref={ref} className={cn("", className)} {...props} />
))
PaginationItem.displayName = "PaginationItem"
type PaginationLinkProps = {
isActive?: boolean
} & Pick<ButtonProps, "size"> &
React.ComponentProps<"a">
const PaginationLink = ({
className,
isActive,
size = "icon",
...props
}: PaginationLinkProps) => (
<a
aria-current={isActive ? "page" : undefined}
className={cn(
buttonVariants({
variant: isActive ? "outline" : "ghost",
size,
}),
className
)}
{...props}
/>
)
PaginationLink.displayName = "PaginationLink"
const PaginationPrevious = ({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn("gap-1 pl-2.5", className)}
{...props}
>
<ChevronLeftIcon className="h-4 w-4" />
<span>Previous</span>
</PaginationLink>
)
PaginationPrevious.displayName = "PaginationPrevious"
const PaginationNext = ({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn("gap-1 pr-2.5", className)}
{...props}
>
<span>Next</span>
<ChevronRightIcon className="h-4 w-4" />
</PaginationLink>
)
PaginationNext.displayName = "PaginationNext"
const PaginationEllipsis = ({
className,
...props
}: React.ComponentProps<"span">) => (
<span
aria-hidden
className={cn("flex h-9 w-9 items-center justify-center", className)}
{...props}
>
<DotsHorizontalIcon className="h-4 w-4" />
<span className="sr-only">More pages</span>
</span>
)
PaginationEllipsis.displayName = "PaginationEllipsis"
export {
Pagination,
PaginationContent,
PaginationLink,
PaginationItem,
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
}

View File

@ -1,40 +0,0 @@
"use client";
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import * as React from "react";
import { cn } from "@/app/common/utils";
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root ref={ref} className={cn("relative overflow-hidden", className)} {...props}>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">{children}</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
));
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" && "h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" && "h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
export { ScrollArea, ScrollBar };

View File

@ -1,113 +0,0 @@
"use client";
import { Cross2Icon } from "@radix-ui/react-icons";
import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva, type VariantProps } from "class-variance-authority";
import * as React from "react";
import { cn } from "@/app/common/utils";
const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-secondary text-foreground",
destructive: "destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
);
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return <ToastPrimitives.Root ref={ref} className={cn(toastVariants({ variant }), className)} {...props} />;
});
Toast.displayName = ToastPrimitives.Root.displayName;
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
));
ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<Cross2Icon className="h-4 w-4" />
</ToastPrimitives.Close>
));
ToastClose.displayName = ToastPrimitives.Close.displayName;
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title ref={ref} className={cn("text-sm font-semibold [&+div]:text-xs", className)} {...props} />
));
ToastTitle.displayName = ToastPrimitives.Title.displayName;
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description ref={ref} className={cn("text-sm opacity-90", className)} {...props} />
));
ToastDescription.displayName = ToastPrimitives.Description.displayName;
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction>;
export {
Toast,
ToastAction,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
type ToastActionElement,
type ToastProps,
};

View File

@ -1,35 +0,0 @@
"use client"
import { useToast } from "@/app/hooks/use-toast"
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/app/components/ui/toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}

View File

@ -1,30 +0,0 @@
"use client"
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/app/common/utils"
const TooltipProvider = TooltipPrimitive.Provider
const Tooltip = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
TooltipContent.displayName = TooltipPrimitive.Content.displayName
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@ -1,11 +0,0 @@
import { useContext } from "react";
import { DatabaseContext } from "../components/loaders/database-loader";
/**
* Gets the database context.
*
* @returns the database context
*/
export default function useDatabase() {
return useContext(DatabaseContext)!;
}

View File

@ -1,194 +0,0 @@
"use client"
// Inspired by react-hot-toast library
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/app/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

View File

@ -1,24 +0,0 @@
import { useEffect, useState } from "react";
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height,
};
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return windowDimensions;
}

View File

@ -1,12 +1,12 @@
import type { Metadata } from "next";
import localFont from "next/font/local";
import BackgroundImage from "./components/background-image";
import DatabaseLoader from "./components/loaders/database-loader";
import NavBar from "./components/navbar/navbar";
import { QueryProvider } from "./components/providers/query-provider";
import { ThemeProvider } from "./components/providers/theme-provider";
import { Toaster } from "./components/ui/toaster";
import { TooltipProvider } from "./components/ui/tooltip";
import BackgroundImage from "../components/background-image";
import DatabaseLoader from "../components/loaders/database-loader";
import NavBar from "../components/navbar/navbar";
import { QueryProvider } from "../components/providers/query-provider";
import { ThemeProvider } from "../components/providers/theme-provider";
import { Toaster } from "../components/ui/toaster";
import { TooltipProvider } from "../components/ui/tooltip";
import "./globals.css";
const siteFont = localFont({