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

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

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

@ -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>
);
}

@ -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 }

@ -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,
}

@ -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 }

@ -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 }

@ -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,
}

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

@ -0,0 +1,8 @@
/**
* Copies the given string to the clipboard
*
* @param str the string to copy
*/
export function copyToClipboard(str: string) {
navigator.clipboard.writeText(str);
}

@ -1,6 +1,6 @@
import ky from "ky"; import ky from "ky";
export default class Leaderboard { export default class DataFetcher {
/** /**
* The name of the leaderboard. * The name of the leaderboard.
*/ */

@ -0,0 +1,49 @@
import { db } from "../../database/database";
import DataFetcher from "../data-fetcher";
import { BeatSaverMap } from "../types/beatsaver/beatsaver-map";
const API_BASE = "https://api.beatsaver.com";
const LOOKUP_MAP_BY_HASH_ENDPOINT = `${API_BASE}/maps/hash/:query`;
class BeatSaverFetcher extends DataFetcher {
constructor() {
super("BeatSaver");
}
/**
* Gets the map that match the query.
*
* @param query the query to search for
* @param useProxy whether to use the proxy or not
* @returns the map that match the query, or undefined if no map were found
*/
async getMapBsr(query: string, useProxy = true): Promise<string | undefined> {
this.log(`Looking up the bsr for the map with hash ${query}...`);
const map = await db.beatSaverMaps.get(query);
// The map is cached
if (map != undefined) {
return map.bsr;
}
const response = await this.fetch<BeatSaverMap>(useProxy, LOOKUP_MAP_BY_HASH_ENDPOINT.replace(":query", query));
// Map not found
if (response == undefined) {
return undefined;
}
const bsr = response.id;
if (bsr == undefined) {
return undefined;
}
// Save map the the db
await db.beatSaverMaps.add({
hash: query,
bsr: bsr,
});
return bsr;
}
}
export const beatsaverFetcher = new BeatSaverFetcher();

@ -1,4 +1,4 @@
import Leaderboard from "../leaderboard"; import DataFetcher from "../data-fetcher";
import { ScoreSort } from "../sort"; import { ScoreSort } from "../sort";
import ScoreSaberPlayer from "../types/scoresaber/scoresaber-player"; import ScoreSaberPlayer from "../types/scoresaber/scoresaber-player";
import ScoreSaberPlayerScoresPage from "../types/scoresaber/scoresaber-player-scores-page"; import ScoreSaberPlayerScoresPage from "../types/scoresaber/scoresaber-player-scores-page";
@ -9,7 +9,7 @@ const SEARCH_PLAYERS_ENDPOINT = `${API_BASE}/players?search=:query`;
const LOOKUP_PLAYER_ENDPOINT = `${API_BASE}/player/:id/full`; 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`; const LOOKUP_PLAYER_SCORES_ENDPOINT = `${API_BASE}/player/:id/scores?limit=:limit&sort=:sort&page=:page`;
class ScoreSaberLeaderboard extends Leaderboard { class ScoreSaberFetcher extends DataFetcher {
constructor() { constructor() {
super("ScoreSaber"); super("ScoreSaber");
} }
@ -72,4 +72,4 @@ class ScoreSaberLeaderboard extends Leaderboard {
} }
} }
export const scoresaberLeaderboard = new ScoreSaberLeaderboard(); export const scoresaberFetcher = new ScoreSaberFetcher();

@ -0,0 +1,51 @@
export default interface BeatSaverAccount {
/**
* The id of the mapper
*/
id: number;
/**
* The name of the mapper.
*/
name: string;
/**
* The account hash of the mapper.
*/
hash: string;
/**
* The avatar url for the mapper.
*/
avatar: string;
/**
* The way the account was created
*/
type: string;
/**
* Whether the account is an admin or not.
*/
admin: boolean;
/**
* Whether the account is a curator or not.
*/
curator: boolean;
/**
* Whether the account is a senior curator or not.
*/
seniorCurator: boolean;
/**
* Whether the account is a verified mapper or not.
*/
verifiedMapper: boolean;
/**
* The playlist for the mappers songs.
*/
playlistUrl: string;
}

@ -0,0 +1,36 @@
export default interface BeatSaverMapMetadata {
/**
* The bpm of the song.
*/
bpm: number;
/**
* The song's length in seconds.
*/
duration: number;
/**
* The song's name.
*/
songName: string;
/**
* The songs sub name.
*/
songSubName: string;
/**
* The artist(s) name.
*/
songAuthorName: string;
/**
* The song's author's url.
*/
songAuthorUrl: string;
/**
* The level mapper(s) name.
*/
levelAuthorName: string;
}

@ -0,0 +1,31 @@
export default interface BeatSaverMapStats {
/**
* The amount of time the map has been played.
*/
plays: number;
/**
* The amount of times the map has been downloaded.
*/
downloads: number;
/**
* The amount of times the map has been upvoted.
*/
upvotes: number;
/**
* The amount of times the map has been downvoted.
*/
downvotes: number;
/**
* The score for the map
*/
score: number;
/**
* The amount of reviews for the map.
*/
reviews: number;
}

@ -0,0 +1,24 @@
import BeatSaverAccount from "./beatsaver-account";
import BeatSaverMapMetadata from "./beatsaver-map-metadata";
import BeatSaverMapStats from "./beatsaver-map-stats";
export interface BeatSaverMap {
id: string;
name: string;
description: string;
uploader: BeatSaverAccount;
metadata: BeatSaverMapMetadata;
stats: BeatSaverMapStats;
uploaded: string;
automapper: boolean;
ranked: boolean;
qualified: boolean;
// todo: versions
createdAt: string;
updatedAt: string;
lastPublishedAt: string;
tags: string[];
declaredAi: string;
blRanked: boolean;
blQualified: boolean;
}

@ -1,5 +1,6 @@
import Dexie, { EntityTable } from "dexie"; import Dexie, { EntityTable } from "dexie";
import { setPlayerIdCookie } from "../website-utils"; import { setPlayerIdCookie } from "../website-utils";
import BeatSaverMap from "./types/beatsaver-map";
import Settings from "./types/settings"; import Settings from "./types/settings";
const SETTINGS_ID = "SSR"; // DO NOT CHANGE const SETTINGS_ID = "SSR"; // DO NOT CHANGE
@ -10,16 +11,23 @@ export default class Database extends Dexie {
*/ */
settings!: EntityTable<Settings, "id">; settings!: EntityTable<Settings, "id">;
/**
* BeatSaver maps
*/
beatSaverMaps!: EntityTable<BeatSaverMap, "hash">;
constructor() { constructor() {
super("ScoreSaberReloaded"); super("ScoreSaberReloaded");
// Stores // Stores
this.version(1).stores({ this.version(1).stores({
settings: "id", settings: "id",
beatSaverMaps: "hash",
}); });
// Mapped tables // Mapped tables
this.settings.mapToClass(Settings); this.settings.mapToClass(Settings);
this.beatSaverMaps.mapToClass(BeatSaverMap);
// Populate default settings if the table is empty // Populate default settings if the table is empty
this.on("populate", () => this.populateDefaults()); this.on("populate", () => this.populateDefaults());

@ -0,0 +1,17 @@
import { Entity } from "dexie";
import Database from "../database";
/**
* A beat saver map.
*/
export default class BeatSaverMap extends Entity<Database> {
/**
* The hash of the map.
*/
hash!: string;
/**
* The bsr code for the map.
*/
bsr!: string;
}

@ -1,4 +1,4 @@
import { config } from "../../../config"; import { config } from "../../config";
/** /**
* Proxies all non-localhost images to make them load faster. * Proxies all non-localhost images to make them load faster.

22
src/common/song-utils.ts Normal file

@ -0,0 +1,22 @@
/**
* Turns a song name and author into a YouTube link
*
* @param name the name of the song
* @param songSubName the sub name of the song
* @param author the author of the song
* @returns the YouTube link for the song
*/
export function songNameToYouTubeLink(name: string, songSubName: string, author: string) {
const baseUrl = "https://www.youtube.com/results?search_query=";
let query = "";
if (name) {
query += `${name} `;
}
if (songSubName) {
query += `${songSubName} `;
}
if (author) {
query += `${author} `;
}
return encodeURI(baseUrl + query.trim().replaceAll(" ", "+"));
}

@ -1,7 +1,7 @@
"use client"; "use client";
import { useLiveQuery } from "dexie-react-hooks"; import { useLiveQuery } from "dexie-react-hooks";
import { config } from "../../../config"; import { config } from "../../config";
import { getImageUrl } from "../common/image-utils"; import { getImageUrl } from "../common/image-utils";
import useDatabase from "../hooks/use-database"; import useDatabase from "../hooks/use-database";

@ -1,8 +1,8 @@
"use client"; "use client";
import { scoresaberLeaderboard } from "@/app/common/leaderboard/impl/scoresaber"; import { scoresaberFetcher } from "@/common/data-fetcher/impl/scoresaber";
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player"; import ScoreSaberPlayer from "@/common/data-fetcher/types/scoresaber/scoresaber-player";
import { formatNumberWithCommas } from "@/app/common/number-utils"; import { formatNumberWithCommas } from "@/common/number-utils";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link"; import Link from "next/link";
import { useState } from "react"; import { useState } from "react";
@ -31,7 +31,7 @@ export default function SearchPlayer() {
async function onSubmit({ username }: z.infer<typeof formSchema>) { async function onSubmit({ username }: z.infer<typeof formSchema>) {
setLoading(true); setLoading(true);
setResults(undefined); // Reset results setResults(undefined); // Reset results
const results = await scoresaberLeaderboard.searchPlayers(username); const results = await scoresaberFetcher.searchPlayers(username);
setResults(results?.players); setResults(results?.players);
setLoading(false); setLoading(false);
} }

@ -0,0 +1,24 @@
type BeatSaverLogoProps = {
size?: number;
className?: string;
};
export default function BeatSaverLogo({ size = 32, className }: BeatSaverLogoProps) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 200 200"
version="1.1"
className={className}
>
<g fill="none" stroke="#fff" strokeWidth="10">
<path d="M 100,7 189,47 100,87 12,47 Z" strokeLinejoin="round"></path>
<path d="M 189,47 189,155 100,196 12,155 12,47" strokeLinejoin="round"></path>
<path d="M 100,87 100,196" strokeLinejoin="round"></path>
<path d="M 26,77 85,106 53,130 Z" strokeLinejoin="round"></path>
</g>
</svg>
);
}

@ -0,0 +1,30 @@
type YouTubeLogoProps = {
size?: number;
className?: string;
};
export default function YouTubeLogo({ size = 32, className }: YouTubeLogoProps) {
return (
<svg
height={size}
width={size}
version="1.1"
id="Layer_1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
viewBox="0 0 461.001 461.001"
xmlSpace="preserve"
className={className}
>
<g>
<path
fill="#F61C0D"
d="M365.257,67.393H95.744C42.866,67.393,0,110.259,0,163.137v134.728
c0,52.878,42.866,95.744,95.744,95.744h269.513c52.878,0,95.744-42.866,95.744-95.744V163.137
C461.001,110.259,418.135,67.393,365.257,67.393z M300.506,237.056l-126.06,60.123c-3.359,1.602-7.239-0.847-7.239-4.568V168.607
c0-3.774,3.982-6.22,7.348-4.514l126.06,63.881C304.363,229.873,304.298,235.248,300.506,237.056z"
/>
</g>
</svg>
);
}

@ -1,6 +1,6 @@
"use client"; "use client";
import useDatabase from "@/app/hooks/use-database"; import useDatabase from "@/hooks/use-database";
import { useLiveQuery } from "dexie-react-hooks"; import { useLiveQuery } from "dexie-react-hooks";
import Link from "next/link"; import Link from "next/link";
import { Avatar, AvatarImage } from "../ui/avatar"; import { Avatar, AvatarImage } from "../ui/avatar";

@ -1,8 +1,8 @@
"use client"; "use client";
import { scoresaberLeaderboard } from "@/app/common/leaderboard/impl/scoresaber"; import { scoresaberFetcher } from "@/common/data-fetcher/impl/scoresaber";
import { ScoreSort } from "@/app/common/leaderboard/sort"; import { ScoreSort } from "@/common/data-fetcher/sort";
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player"; import ScoreSaberPlayer from "@/common/data-fetcher/types/scoresaber/scoresaber-player";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import PlayerHeader from "./player-header"; import PlayerHeader from "./player-header";
import PlayerRankChart from "./player-rank-chart"; import PlayerRankChart from "./player-rank-chart";
@ -20,7 +20,7 @@ export default function PlayerData({ initalPlayerData, sort, page }: Props) {
let player = initalPlayerData; let player = initalPlayerData;
const { data, isLoading, isError } = useQuery({ const { data, isLoading, isError } = useQuery({
queryKey: ["player", player.id], queryKey: ["player", player.id],
queryFn: () => scoresaberLeaderboard.lookupPlayer(player.id), queryFn: () => scoresaberFetcher.lookupPlayer(player.id),
refetchInterval: REFRESH_INTERVAL, refetchInterval: REFRESH_INTERVAL,
}); });

@ -1,5 +1,5 @@
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player"; import ScoreSaberPlayer from "@/common/data-fetcher/types/scoresaber/scoresaber-player";
import { formatNumberWithCommas } from "@/app/common/number-utils"; import { formatNumberWithCommas } from "@/common/number-utils";
import { GlobeAmericasIcon } from "@heroicons/react/24/solid"; import { GlobeAmericasIcon } from "@heroicons/react/24/solid";
import Card from "../card"; import Card from "../card";
import CountryFlag from "../country-flag"; import CountryFlag from "../country-flag";

@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
"use client"; "use client";
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player"; import ScoreSaberPlayer from "@/common/data-fetcher/types/scoresaber/scoresaber-player";
import { formatNumberWithCommas } from "@/app/common/number-utils"; import { formatNumberWithCommas } from "@/common/number-utils";
import { CategoryScale, Chart, Legend, LinearScale, LineElement, PointElement, Title, Tooltip } from "chart.js"; import { CategoryScale, Chart, Legend, LinearScale, LineElement, PointElement, Title, Tooltip } from "chart.js";
import { Line } from "react-chartjs-2"; import { Line } from "react-chartjs-2";
import Card from "../card"; import Card from "../card";

@ -1,17 +1,17 @@
"use client"; "use client";
import { scoresaberLeaderboard } from "@/app/common/leaderboard/impl/scoresaber"; import { scoresaberFetcher } from "@/common/data-fetcher/impl/scoresaber";
import { ScoreSort } from "@/app/common/leaderboard/sort"; import { ScoreSort } from "@/common/data-fetcher/sort";
import ScoreSaberPlayer from "@/app/common/leaderboard/types/scoresaber/scoresaber-player"; import ScoreSaberPlayer from "@/common/data-fetcher/types/scoresaber/scoresaber-player";
import ScoreSaberPlayerScoresPage from "@/app/common/leaderboard/types/scoresaber/scoresaber-player-scores-page"; import ScoreSaberPlayerScoresPage from "@/common/data-fetcher/types/scoresaber/scoresaber-player-scores-page";
import { capitalizeFirstLetter } from "@/app/common/string-utils"; import { capitalizeFirstLetter } from "@/common/string-utils";
import useWindowDimensions from "@/app/hooks/use-window-dimensions"; import useWindowDimensions from "@/hooks/use-window-dimensions";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import Card from "../card"; import Card from "../card";
import Pagination from "../input/pagination"; import Pagination from "../input/pagination";
import { Button } from "../ui/button"; import { Button } from "../ui/button";
import Score from "./score"; import Score from "./score/score";
type Props = { type Props = {
player: ScoreSaberPlayer; player: ScoreSaberPlayer;
@ -27,7 +27,7 @@ export default function PlayerScores({ player, sort, page }: Props) {
const { data, isError, refetch } = useQuery({ const { data, isError, refetch } = useQuery({
queryKey: ["playerScores", player.id, currentSort, currentPage], queryKey: ["playerScores", player.id, currentSort, currentPage],
queryFn: () => scoresaberLeaderboard.lookupPlayerScores(player.id, currentSort, currentPage), queryFn: () => scoresaberFetcher.lookupPlayerScores(player.id, currentSort, currentPage),
}); });
useEffect(() => { useEffect(() => {

@ -0,0 +1,40 @@
import { Tooltip, TooltipContent, TooltipTrigger } from "../../ui/tooltip";
type Props = {
/**
* The button content.
*/
children: React.ReactNode;
/**
* The tooltip content.
*/
tooltip?: React.ReactNode;
/**
* Callback for when the button is clicked.
*/
onClick: () => void;
};
export default function ScoreButton({ children, tooltip, onClick }: Props) {
const button = (
<button
className="bg-accent rounded-md flex justify-center items-center p-1 w-[28px] h-[28px] hover:brightness-75 transform-gpu transition-all"
onClick={onClick}
>
{children}
</button>
);
if (tooltip) {
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent>{tooltip}</TooltipContent>
</Tooltip>
);
}
return button;
}

@ -0,0 +1,106 @@
"use client";
import { beatsaverFetcher } from "@/common/data-fetcher/impl/beatsaver";
import ScoreSaberPlayerScore from "@/common/data-fetcher/types/scoresaber/scoresaber-player-score";
import { formatNumberWithCommas } from "@/common/number-utils";
import { songNameToYouTubeLink } from "@/common/song-utils";
import { timeAgo } from "@/common/time-utils";
import YouTubeLogo from "@/components/logos/youtube-logo";
import { useToast } from "@/hooks/use-toast";
import { GlobeAmericasIcon } from "@heroicons/react/24/solid";
import Image from "next/image";
import { useEffect, useState } from "react";
import BeatSaverLogo from "../../logos/beatsaver-logo";
import ScoreButton from "./score-button";
type Props = {
/**
* The score to display.
*/
playerScore: ScoreSaberPlayerScore;
};
export default function Score({ playerScore }: Props) {
const { score, leaderboard } = playerScore;
const { toast } = useToast();
const [bsr, setBsr] = useState<string | undefined>();
useEffect(() => {
(async () => {
const bsrFound = await beatsaverFetcher.getMapBsr(leaderboard.songHash);
setBsr(bsrFound);
})();
}, [playerScore]);
return (
<div className="grid gap-2 md:gap-0 pb-2 pt-2 first:pt-0 last:pb-0 grid-cols-[20px 1fr_1fr] md:grid-cols-[0.85fr_5fr_1fr_1.2fr]">
<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">#{formatNumberWithCommas(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 className="text-pp text-ellipsis">{leaderboard.songName}</p>
<p className="text-sm text-gray-400 text-ellipsis">{leaderboard.songAuthorName}</p>
<p className="text-sm text-ellipsis">{leaderboard.levelAuthorName}</p>
</div>
</div>
</div>
<div className="hidden md:flex flex-row flex-wrap gap-1 justify-end">
{bsr != undefined && (
<>
{/* Copy BSR */}
<ScoreButton
onClick={() => {
toast({
title: "Copied!",
description: `Copied "!bsr ${bsr}" to your clipboard!`,
});
}}
tooltip={<p>Click to copy the bsr code</p>}
>
<p>!</p>
</ScoreButton>
{/* Open map in BeatSaver */}
<ScoreButton
onClick={() => {
window.open(`https://beatsaver.com/maps/${bsr}`, "_blank");
}}
tooltip={<p>Click to open the map</p>}
>
<BeatSaverLogo />
</ScoreButton>
</>
)}
{/* Open song in YouTube */}
<ScoreButton
onClick={() => {
window.open(
songNameToYouTubeLink(leaderboard.songName, leaderboard.songSubName, leaderboard.songAuthorName),
"_blank"
);
}}
tooltip={<p>Click to open the song in YouTube</p>}
>
<YouTubeLogo />
</ScoreButton>
</div>
<div className="flex justify-end">stats stuff</div>
</div>
);
}

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

@ -1,22 +1,18 @@
import * as React from "react" import { Slot } from "@radix-ui/react-slot";
import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority";
import { cva, type VariantProps } from "class-variance-authority" import * as React from "react";
import { cn } from "@/app/common/utils" import { cn } from "@/common/utils";
const buttonVariants = cva( 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", "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: { variants: {
variant: { variant: {
default: default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
"bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
destructive: outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
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", ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline", link: "text-primary underline-offset-4 hover:underline",
}, },
@ -32,26 +28,20 @@ const buttonVariants = cva(
size: "default", size: "default",
}, },
} }
) );
export interface ButtonProps export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>, extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> { VariantProps<typeof buttonVariants> {
asChild?: boolean asChild?: boolean;
} }
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => { ({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button" const Comp = asChild ? Slot : "button";
return ( return <Comp className={cn(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
} }
) );
Button.displayName = "Button" Button.displayName = "Button";
export { Button, buttonVariants } export { Button, buttonVariants };

@ -0,0 +1,41 @@
import * as React from "react";
import { cn } from "@/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, CardContent, CardDescription, CardFooter, CardHeader, CardTitle };

138
src/components/ui/form.tsx Normal file

@ -0,0 +1,138 @@
"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 "@/common/utils";
import { Label } from "@/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 };

@ -0,0 +1,22 @@
import * as React from "react";
import { cn } from "@/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 };

@ -0,0 +1,19 @@
"use client";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cva, type VariantProps } from "class-variance-authority";
import * as React from "react";
import { cn } from "@/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 };

@ -0,0 +1,81 @@
import * as React from "react";
import { ChevronLeftIcon, ChevronRightIcon, DotsHorizontalIcon } from "@radix-ui/react-icons";
import { cn } from "@/common/utils";
import { ButtonProps, buttonVariants } from "@/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,
};

@ -3,7 +3,7 @@
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"; import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
import * as React from "react"; import * as React from "react";
import { cn } from "@/app/common/utils"; import { cn } from "@/common/utils";
const ScrollArea = React.forwardRef< const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>, React.ElementRef<typeof ScrollAreaPrimitive.Root>,

@ -5,7 +5,7 @@ import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva, type VariantProps } from "class-variance-authority"; import { cva, type VariantProps } from "class-variance-authority";
import * as React from "react"; import * as React from "react";
import { cn } from "@/app/common/utils"; import { cn } from "@/common/utils";
const ToastProvider = ToastPrimitives.Provider; const ToastProvider = ToastPrimitives.Provider;

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

@ -1,15 +1,15 @@
"use client" "use client";
import * as React from "react" import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import * as TooltipPrimitive from "@radix-ui/react-tooltip" import * as React from "react";
import { cn } from "@/app/common/utils" import { cn } from "@/common/utils";
const TooltipProvider = TooltipPrimitive.Provider const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef< const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>, React.ElementRef<typeof TooltipPrimitive.Content>,
@ -24,7 +24,7 @@ const TooltipContent = React.forwardRef<
)} )}
{...props} {...props}
/> />
)) ));
TooltipContent.displayName = TooltipPrimitive.Content.displayName TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };

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