Compare commits

...

7 Commits

10 changed files with 1365 additions and 80 deletions

View File

@ -15,5 +15,5 @@
## Shell command guidance
- Whitelisted commands: `grep`
- DO NOT USE: `cd` (prefer `pwd`)
- Dont' use `cd`, prefer `pwd`
- Dont' use `rg`, prefer `grep -r`

View File

@ -29,6 +29,18 @@ body {
@apply bg-bg text-white/90 antialiased;
}
p a {
color: var(--color-neon);
text-decoration: underline;
text-decoration-color: rgba(34, 211, 238, 0.4);
transition: color 0.2s ease, text-decoration-color 0.2s ease;
}
p a:hover {
color: color-mix(in srgb, var(--color-neon) 80%, white 20%);
text-decoration-color: rgba(34, 211, 238, 0.85);
}
/* Utilities */
@utility btn-neon {
@apply inline-flex items-center gap-2 rounded-md border border-neon/60 px-4 py-2 text-neon transition hover:border-neon hover:text-white focus:outline-none focus:ring-2 focus:ring-neon/50;

View File

@ -3,63 +3,69 @@
import MapActionButtons from './MapActionButtons.svelte';
import SongPlayer from './SongPlayer.svelte';
// Song metadata
export let hash: string;
export let coverURL: string | undefined = undefined;
export let songName: string | undefined = undefined;
export let mapper: string | undefined = undefined;
export let stars: number | undefined = undefined;
export let timeset: number | undefined = undefined;
// Song metadata
export let hash: string;
export let coverURL: string | undefined = undefined;
export let songName: string | undefined = undefined;
export let mapper: string | undefined = undefined;
export let stars: number | undefined = undefined;
export let timeset: number | undefined = undefined;
// Difficulty info
export let diffName: string;
export let modeName: string = 'Standard';
// Difficulty info
export let diffName: string;
export let modeName: string = 'Standard';
// BeatLeader/BeatSaver links
export let leaderboardId: string | undefined = undefined;
export let beatsaverKey: string | undefined = undefined;
// BeatLeader/BeatSaver links
export let leaderboardId: string | undefined = undefined;
export let beatsaverKey: string | undefined = undefined;
// Layout tweaks
export let compact = false;
export let showActions = true;
export let showPublished = true;
</script>
<div class="aspect-square bg-black/30">
<div class:compact-wrapper={compact} class="card-wrapper">
<div class:compact-cover={compact} class="cover">
{#if coverURL}
<img
src={coverURL}
alt={songName ?? hash}
loading="lazy"
class="h-full w-full object-cover"
/>
<img src={coverURL} alt={songName ?? hash} loading="lazy" />
{:else}
<div class="h-full w-full flex items-center justify-center text-2xl">☁️</div>
<div class="placeholder">☁️</div>
{/if}
</div>
<div class="p-3">
<div class="font-semibold truncate" title={songName ?? hash}>
</div>
<div class:compact-body={compact} class="body">
<div class="title" title={songName ?? hash}>
{songName ?? hash}
</div>
{#if mapper}
<div class="mt-0.5 text-xs text-muted truncate flex items-center justify-between">
<span>
<div class="mapper-row">
<span class="mapper">
{mapper}
{#if stars !== undefined}
<span class="ml-3" title="BeatLeader star rating">{stars.toFixed(2)}</span>
<span class="stars" title="BeatLeader star rating">{stars.toFixed(2)}</span>
{/if}
</span>
{#if timeset !== undefined}
<span class="text-[11px] ml-2">{new Date(timeset * 1000).toLocaleDateString()}</span>
{#if showPublished && timeset !== undefined}
<span class="date">{new Date(timeset * 1000).toLocaleDateString()}</span>
{/if}
</div>
{/if}
<div class="mt-2 flex items-center gap-2">
<div class:compact-row={compact} class="meta">
<div class:compact-leading={compact} class="meta-leading">
<slot name="meta-leading">
<DifficultyLabel {diffName} {modeName} />
<div class="flex-1">
</slot>
</div>
<div class="player">
<SongPlayer {hash} preferBeatLeader={true} />
</div>
</div>
<slot name="content" />
<div class="mt-3">
{#if showActions}
<div class="actions">
<MapActionButtons
{hash}
{leaderboardId}
@ -68,5 +74,179 @@
{beatsaverKey}
/>
</div>
{/if}
</div>
</div>
<style>
.card-wrapper {
display: flex;
flex-direction: column;
gap: 0.75rem;
width: 100%;
}
.card-wrapper.compact-wrapper {
display: grid;
grid-template-columns: auto 1fr;
align-items: stretch;
column-gap: 0.6rem;
}
.cover {
position: relative;
width: 100%;
padding-top: 100%;
background: rgba(0, 0, 0, 0.3);
border-radius: 0.75rem;
overflow: hidden;
}
.cover img,
.cover .placeholder {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.cover .placeholder {
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
}
.cover.compact-cover {
width: 104px;
min-width: 104px;
max-width: 104px;
padding-top: 104px;
border-radius: 0.5rem;
}
.body {
padding: 0.75rem 0.75rem 1rem;
display: flex;
flex-direction: column;
flex: 1;
}
.body.compact-body {
padding: 0.25rem 0.2rem 0.5rem;
gap: 0.4rem;
min-width: 0;
}
.title {
font-weight: 600;
font-size: 1rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.body.compact-body .title {
font-size: 0.95rem;
}
.mapper-row {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.5rem;
font-size: 0.75rem;
color: rgba(148, 163, 184, 0.9);
}
.mapper-row .mapper {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mapper-row .stars {
margin-left: 0.4rem;
}
.mapper-row .date {
font-size: 0.7rem;
white-space: nowrap;
}
.meta {
margin-top: 0.6rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.meta-leading {
display: flex;
align-items: center;
gap: 0.35rem;
min-width: 0;
flex: 1;
}
.meta-leading.compact-leading {
width: 100%;
}
.meta-leading :global(.score-meter) {
width: 100%;
}
.meta.compact-row {
margin-top: 0.25rem;
gap: 0.35rem;
}
.player {
flex: 1;
}
.actions {
margin-top: auto;
}
.body.compact-body .actions {
margin-top: 0.3rem;
}
@media (max-width: 959px) {
.card-wrapper.compact-wrapper {
grid-template-columns: 1fr;
row-gap: 0.35rem;
}
.cover.compact-cover {
margin: 0 auto;
width: 100%;
max-width: 240px;
padding-top: 100%;
}
}
@media (min-width: 960px) {
.meta.compact-row {
flex-direction: column;
align-items: flex-start;
gap: 0.2rem;
}
.meta.compact-row .meta-leading {
width: 100%;
}
.meta.compact-row .player {
width: 100%;
}
}
:global(.difficulty-label) {
white-space: nowrap;
}
</style>

View File

@ -0,0 +1,117 @@
<script lang="ts">
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
export let value: number | null | undefined = null;
export let min = 0;
export let max = 1;
export let decimals = 1;
export let showLabel = false;
export let label: string | null = null;
export let emptyLabel = '—';
export let size: 'sm' | 'md' | 'lg' = 'md';
export let className = '';
const { class: restClass = '', ...restProps } = $$restProps;
const effectiveRange = () => {
const span = max - min;
return span === 0 ? 1 : Math.abs(span);
};
const normaliseValue = (input: number) => min + clamp(input - min, 0, effectiveRange());
const percentFromValue = (input: number | null | undefined) => {
if (typeof input !== 'number' || !Number.isFinite(input)) return null;
const bounded = clamp((input - min) / effectiveRange(), 0, 1);
return bounded * 100;
};
$: percent = percentFromValue(value);
$: hasValue = percent !== null;
$: fill = hasValue ? `${percent!.toFixed(2)}%` : '0%';
$: displayLabel = label ?? (hasValue ? `${percent!.toFixed(decimals)}%` : emptyLabel);
$: ariaValueNow = hasValue ? normaliseValue(value as number) : undefined;
$: ariaValueText = hasValue ? `${percent!.toFixed(decimals)} percent` : 'Not available';
$: classes = [`score-meter`, `score-meter--${size}`, restClass, className].filter(Boolean).join(' ');
</script>
<div
{...restProps}
class={classes}
class:score-meter--empty={!hasValue}
data-testid="score-meter"
>
<div
class="score-meter__track"
role="meter"
aria-valuemin={min}
aria-valuemax={max}
aria-valuenow={ariaValueNow}
aria-valuetext={ariaValueText}
style={`--score-meter-fill:${fill}`}
></div>
{#if showLabel}
<span class="score-meter__label">{displayLabel}</span>
{/if}
</div>
<style>
.score-meter {
--score-meter-height: 0.5rem;
--score-meter-track: rgba(34, 211, 238, 0.15);
--score-meter-gradient: linear-gradient(90deg, var(--color-neon-fuchsia), var(--color-neon));
--score-meter-label-color: rgba(148, 163, 184, 0.92);
display: inline-flex;
align-items: center;
gap: 0.5rem;
width: 100%;
min-width: 0;
}
.score-meter--sm {
--score-meter-height: 0.45rem;
}
.score-meter--lg {
--score-meter-height: 0.6rem;
}
.score-meter__track {
position: relative;
flex: 1;
min-width: 60px;
height: var(--score-meter-height);
border-radius: 999px;
background-color: var(--score-meter-track);
overflow: hidden;
}
.score-meter__track::before {
content: '';
position: absolute;
inset: 0;
border-radius: inherit;
background: var(--score-meter-gradient);
-webkit-mask-image: linear-gradient(
90deg,
#000 0 var(--score-meter-fill, 0%),
transparent var(--score-meter-fill, 0%) 100%
);
mask-image: linear-gradient(90deg, #000 0 var(--score-meter-fill, 0%), transparent var(--score-meter-fill, 0%) 100%);
clip-path: inset(0 calc(100% - var(--score-meter-fill, 0%)) 0 0 round 999px);
transition: -webkit-mask-image 0.3s ease, mask-image 0.3s ease, clip-path 0.3s ease;
}
.score-meter__label {
font-size: 0.85rem;
color: var(--score-meter-label-color);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.score-meter--empty .score-meter__label {
opacity: 0.6;
}
</style>

View File

@ -1,4 +1,11 @@
import * as nodeFs from 'node:fs';
import * as nodePath from 'node:path';
import * as nodeOs from 'node:os';
const BASE_URL = 'https://api.beatsaver.com';
// Many API calls are undocumented and only work on the web API, e.g. searchPlaylists
const WEB_API_BASE_URL = 'https://beatsaver.com/api';
const CACHE_ROOT = '.data/beatsaver-cache';
type QueryParams = Record<string, string | number | boolean | undefined | null>;
@ -28,6 +35,183 @@ export interface EnvironmentMapInfo extends CuratedSongInfo {
environment?: string;
}
type DateInput = string | number | Date;
export interface BeatSaverUser {
id: number;
name: string;
avatar: string;
description?: string | null;
hash?: string | null;
verifiedMapper?: boolean;
[key: string]: unknown;
}
export interface PlaylistStats {
totalMaps: number;
mapperCount: number;
totalDuration: number;
minNps: number;
maxNps: number;
upVotes: number;
downVotes: number;
avgScore: number;
[key: string]: unknown;
}
export interface PlaylistBasic {
playlistId: number;
playlistImage: string;
name: string;
type: string;
owner: number;
config?: unknown;
[key: string]: unknown;
}
export interface PlaylistFull {
playlistId: number;
name: string;
description: string;
playlistImage: string;
playlistImage512?: string | null;
owner: BeatSaverUser;
curator?: BeatSaverUser | null;
stats?: PlaylistStats | null;
createdAt?: string;
updatedAt?: string;
songsChangedAt?: string | null;
curatedAt?: string | null;
deletedAt?: string | null;
downloadURL: string;
type: string;
config?: unknown;
[key: string]: unknown;
}
export interface MapMetadata {
bpm: number;
duration: number;
songName: string;
songSubName: string;
songAuthorName: string;
levelAuthorName: string;
[key: string]: unknown;
}
export interface MapStats {
plays: number;
downloads: number;
upvotes: number;
downvotes: number;
score: number;
reviews?: number;
sentiment?: unknown;
[key: string]: unknown;
}
export interface MapDifficulty {
njs: number;
offset: number;
notes: number;
bombs: number;
obstacles: number;
nps: number;
length: number;
characteristic: string;
difficulty: string;
events: number;
chroma: boolean;
me: boolean;
ne: boolean;
cinema: boolean;
vivify?: boolean;
seconds: number;
stars?: number;
maxScore: number;
label?: string | null;
blStars?: number | null;
environment?: string | null;
[key: string]: unknown;
}
export interface MapVersion {
hash: string;
key?: string | null;
state: string;
createdAt: string;
downloadURL: string;
coverURL: string;
previewURL: string;
diffs?: MapDifficulty[];
feedback?: string | null;
testplayAt?: string | null;
testplays?: unknown;
scheduledAt?: string | null;
[key: string]: unknown;
}
export interface MapDetail {
id: string;
name: string;
description: string;
uploader: BeatSaverUser;
metadata: MapMetadata;
stats: MapStats;
versions: MapVersion[];
curator?: BeatSaverUser | null;
curatedAt?: string | null;
createdAt?: string;
updatedAt?: string;
lastPublishedAt?: string | null;
automapper?: boolean;
ranked?: boolean;
qualified?: boolean;
tags?: unknown;
bookmarked?: boolean | null;
collaborators?: BeatSaverUser[] | null;
declaredAi?: unknown;
blRanked?: boolean;
blQualified?: boolean;
nsfw?: boolean;
[key: string]: unknown;
}
export interface MapDetailWithOrder {
map: MapDetail;
order: number;
}
export interface PlaylistPage {
playlist: PlaylistFull | null;
maps: MapDetailWithOrder[] | null;
}
export interface PlaylistSearchResponse<T = PlaylistFull> {
docs: T[];
info?: unknown;
}
export interface PlaylistSearchParams {
query?: string;
page?: number;
sortOrder?: string;
order?: string;
ascending?: boolean;
includeEmpty?: boolean;
curated?: boolean;
verified?: boolean;
minNps?: number;
maxNps?: number;
from?: DateInput;
to?: DateInput;
}
export interface PlaylistDetailOptions {
page?: number | null;
useCache?: boolean;
}
interface BeatSaverApiOptions {
cacheExpiryDays?: number;
cacheDir?: string;
@ -198,6 +382,90 @@ export class BeatSaverAPI {
return processed;
}
async searchPlaylists(params: PlaylistSearchParams = {}): Promise<PlaylistSearchResponse> {
const {
query = '',
page = 0,
sortOrder = 'Relevance',
order,
ascending,
includeEmpty,
curated,
verified,
minNps,
maxNps,
from,
to
} = params;
const normalizeDate = (value?: DateInput): string | undefined => {
if (value === undefined || value === null) return undefined;
if (value instanceof Date) return value.toISOString();
if (typeof value === 'number') return new Date(value).toISOString();
return value;
};
const url = `${WEB_API_BASE_URL}/playlists/search/${page}${buildQuery({
q: query,
sortOrder,
order,
ascending,
includeEmpty,
curated,
verified,
minNps,
maxNps,
from: normalizeDate(from),
to: normalizeDate(to)
})}`;
const res = await this.request(url);
if (!res.ok) throw new Error(`BeatSaver searchPlaylists failed: ${res.status}`);
return (await res.json()) as PlaylistSearchResponse;
}
async getPlaylistDetail(
playlistId: number | string,
options: PlaylistDetailOptions = {}
): Promise<PlaylistPage> {
const { page = null, useCache = true } = options;
const rawId = String(playlistId);
const safeId = encodeURIComponent(rawId);
const cacheSafeId = rawId.replace(/[^a-zA-Z0-9_-]/g, '_');
const pageSuffix = page === null ? 'detail' : `page_${page}`;
const cachePath = this.pathJoin(this.cacheDir, `playlist_${cacheSafeId}_${pageSuffix}.json`);
if (useCache && (await this.isCacheValid(cachePath))) {
const cached = await this.readCache<PlaylistPage>(cachePath);
if (cached) return cached;
}
const endpoint =
page === null
? `${WEB_API_BASE_URL}/playlists/id/${safeId}`
: `${WEB_API_BASE_URL}/playlists/id/${safeId}/${page}`;
const res = await this.request(endpoint);
if (!res.ok) throw new Error(`BeatSaver getPlaylistDetail failed: ${res.status}`);
const payload = (await res.json()) as PlaylistPage;
if (useCache) {
await this.writeCache(cachePath, payload);
}
return payload;
}
async getPlaylistMaps(
playlistId: number | string,
page = 0,
options: { useCache?: boolean } = {}
): Promise<MapDetailWithOrder[]> {
const { useCache = true } = options;
const detail = await this.getPlaylistDetail(playlistId, { page, useCache });
return detail.maps ?? [];
}
async getMapByHash(mapHash: string): Promise<unknown> {
const url = `${BASE_URL}/maps/hash/${encodeURIComponent(mapHash)}`;
const res = await this.request(url);
@ -263,17 +531,8 @@ export class BeatSaverAPI {
}
private determineCacheDir(): string {
// Prefer ~/.cache/saberlist/beatsaver, fallback to CWD .cache
const os = this.osModule();
const path = this.pathModule();
const home = os.homedir?.();
const homeCache = home ? path.join(home, '.cache') : null;
if (homeCache) {
const saberlist = path.join(homeCache, 'saberlist');
const beatsaver = path.join(saberlist, 'beatsaver');
return beatsaver;
}
return this.pathJoin(process.cwd(), '.cache');
return this.pathJoin(process.cwd(), CACHE_ROOT);
}
private ensureCacheDir(): void {
@ -304,26 +563,26 @@ export class BeatSaverAPI {
// Lazy require Node builtins to keep SSR-friendly import graph
private fsPromises() {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const fs = require('fs');
return fs.promises as typeof import('fs').promises;
return nodeFs.promises;
}
private fsModule() {
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require('fs') as typeof import('fs');
return nodeFs;
}
private pathModule() {
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require('path') as typeof import('path');
return nodePath;
}
private osModule() {
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require('os') as typeof import('os');
return nodeOs;
}
}
export function createBeatSaverAPI(fetchFn: typeof fetch, options: BeatSaverApiOptions = {}): BeatSaverAPI {
return new BeatSaverAPI(fetchFn, options);
const mergedOptions: BeatSaverApiOptions = {
...options,
cacheExpiryDays: options.cacheExpiryDays ?? 90
};
return new BeatSaverAPI(fetchFn, mergedOptions);
}

View File

@ -105,7 +105,8 @@ const DEFAULT_PRIVATE_TOOL_REQUIREMENT: ToolRequirement = {
export const TOOL_REQUIREMENTS = {
'compare-histories': DEFAULT_PRIVATE_TOOL_REQUIREMENT,
'player-headtohead': DEFAULT_PRIVATE_TOOL_REQUIREMENT,
'player-playlist-gaps': DEFAULT_PRIVATE_TOOL_REQUIREMENT
'player-playlist-gaps': DEFAULT_PRIVATE_TOOL_REQUIREMENT,
'playlist-discovery': DEFAULT_PRIVATE_TOOL_REQUIREMENT
} as const satisfies Record<string, ToolRequirement>;
export type ToolKey = keyof typeof TOOL_REQUIREMENTS;

View File

@ -6,7 +6,8 @@
{#each [
{ name: 'Compare Play Histories', href: '/tools/compare-histories', desc: 'Find songs A played that B has not' },
{ name: 'Player Playlist Gaps', href: '/tools/player-playlist-gaps', desc: 'Upload a playlist and find songs a player has not played' },
{ name: 'Player Head-to-Head', href: '/tools/player-headtohead', desc: 'Compare two players on the same map/difficulty' }
{ name: 'Player Head-to-Head', href: '/tools/player-headtohead', desc: 'Compare two players on the same map/difficulty' },
{ name: 'Playlist Discovery', href: '/tools/playlist-discovery', desc: 'Browse verified BeatSaver playlists sorted by recency' }
] as tool}
<a href={tool.href} class="card-surface p-5 block">
<div class="font-semibold">{tool.name}</div>

View File

@ -0,0 +1,76 @@
import { createBeatSaverAPI, type PlaylistFull, type PlaylistSearchResponse } from '$lib/server/beatsaver';
import type { PageServerLoad } from './$types';
function parsePositiveInt(value: string | null, fallback: number): number {
if (!value) return fallback;
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed <= 0) return fallback;
return parsed;
}
type SearchInfoShape = {
page?: number;
pages?: number;
total?: number;
size?: number;
itemsPerPage?: number;
};
export const load: PageServerLoad = async ({ url, fetch, parent }) => {
const parentData = await parent();
const requestedPage = parsePositiveInt(url.searchParams.get('page'), 1);
const pageIndex = requestedPage - 1;
const api = createBeatSaverAPI(fetch);
const MIN_MAPS = 3;
try {
const response = (await api.searchPlaylists({
page: pageIndex,
sortOrder: 'Latest',
verified: true,
includeEmpty: false
})) as PlaylistSearchResponse<PlaylistFull>;
const docsRaw = Array.isArray(response?.docs) ? response.docs : [];
const docs = docsRaw.filter((playlist) => {
const totalMaps = playlist?.stats?.totalMaps ?? 0;
return Number.isFinite(totalMaps) && totalMaps >= MIN_MAPS;
});
const info = (response?.info && typeof response.info === 'object' ? (response.info as SearchInfoShape) : null) ?? null;
const infoPage = typeof info?.page === 'number' ? info.page : pageIndex;
const currentPage = infoPage + 1;
const totalPages = typeof info?.pages === 'number' ? info.pages : null;
const total = typeof info?.total === 'number' ? info.total : null;
const pageSize = typeof info?.size === 'number'
? info.size
: typeof info?.itemsPerPage === 'number'
? info.itemsPerPage
: docs.length;
return {
...parentData,
playlists: docs,
info,
page: currentPage,
totalPages,
total,
pageSize,
error: null
};
} catch (err) {
console.error('Failed to load BeatSaver playlists', err);
return {
...parentData,
playlists: [] as PlaylistFull[],
info: null,
page: requestedPage,
totalPages: null,
total: null,
pageSize: 0,
error: err instanceof Error ? err.message : 'Failed to load playlists'
};
}
};

View File

@ -0,0 +1,602 @@
<script lang="ts">
import HasToolAccess from '$lib/components/HasToolAccess.svelte';
import MapCard from '$lib/components/MapCard.svelte';
import ScoreBar from '$lib/components/ScoreBar.svelte';
import type { MapDetailWithOrder, MapDetail, MapVersion, MapDifficulty, PlaylistFull } from '$lib/server/beatsaver';
import type { BeatLeaderPlayerProfile } from '$lib/utils/plebsaber-utils';
import { TOOL_REQUIREMENTS } from '$lib/utils/plebsaber-utils';
type PlaylistWithStats = PlaylistFull & { stats?: PlaylistFull['stats'] };
type PlaylistSongCard = {
id: string;
hash: string;
coverURL?: string;
songName: string;
mapper?: string;
timeset?: number;
diffName: string;
modeName: string;
beatsaverKey?: string;
publishedLabel: string;
score?: number | null;
};
type PlaylistState = {
loading: boolean;
maps: PlaylistSongCard[];
error: string | null;
total: number | null;
offset: number;
};
const SONGS_PER_PAGE = 12;
export let data: {
playlists: PlaylistWithStats[];
page: number;
totalPages: number | null;
total: number | null;
pageSize: number;
error: string | null;
player: BeatLeaderPlayerProfile | null;
adminRank: number | null;
adminPlayer: BeatLeaderPlayerProfile | null;
};
const requirement = TOOL_REQUIREMENTS['playlist-discovery'];
const playlistBaseUrl = 'https://beatsaver.com/playlists/';
const profileBaseUrl = 'https://beatsaver.com/profile/';
$: playlists = data?.playlists ?? [];
$: page = data?.page ?? 1;
$: totalPages = data?.totalPages ?? null;
$: total = data?.total ?? null;
$: pageSize = data?.pageSize ?? 0;
$: hasPrev = page > 1;
$: hasNext = totalPages != null ? page < totalPages : playlists.length > 0 && playlists.length === pageSize;
$: prevHref = hasPrev ? `?page=${page - 1}` : null;
$: nextHref = hasNext ? `?page=${page + 1}` : null;
let expanded: Record<number, boolean> = {};
let playlistState: Record<number, PlaylistState> = {};
function togglePlaylist(id: number) {
const currentlyExpanded = Boolean(expanded[id]);
const nextExpanded: Record<number, boolean> = {};
if (!currentlyExpanded) {
nextExpanded[id] = true;
}
expanded = nextExpanded;
if (!currentlyExpanded) {
const state = playlistState[id];
const currentOffset = state && typeof state.offset === 'number' ? state.offset : 0;
loadPlaylistMaps(id, currentOffset);
}
}
async function loadPlaylistMaps(id: number, offset = 0) {
playlistState = {
...playlistState,
[id]: { loading: true, maps: playlistState[id]?.maps ?? [], error: null, total: playlistState[id]?.total ?? null, offset }
};
try {
const res = await fetch(`/tools/playlist-discovery/playlist?id=${encodeURIComponent(String(id))}&offset=${offset}`);
if (!res.ok) throw new Error(`Failed to load playlist ${id}: ${res.status}`);
const payload = (await res.json()) as { maps?: MapDetailWithOrder[] | null; totalCount?: number | null; offset: number; pageSize?: number };
const maps = Array.isArray(payload?.maps) ? payload.maps : [];
const cards = maps
.map((entry) => mapEntryToCard(entry))
.filter((card): card is PlaylistSongCard => card !== null);
playlistState = {
...playlistState,
[id]: {
loading: false,
maps: cards,
error: null,
total:
typeof payload?.totalCount === 'number'
? payload.totalCount
: playlistState[id]?.total ?? (offset + cards.length),
offset: payload?.offset ?? offset
}
};
} catch (err) {
playlistState = {
...playlistState,
[id]: { loading: false, maps: [], error: err instanceof Error ? err.message : 'Failed to load playlist songs', total: null, offset }
};
}
}
function getPublishedVersion(map: MapDetail | undefined | null) {
const versions = map?.versions ?? [];
return versions.find((v) => v.state === 'Published') ?? versions[0];
}
function getPrimaryDifficulty(version: MapVersion | undefined | null): MapDifficulty | null {
const diffs = version?.diffs ?? [];
return diffs.length > 0 ? diffs[0] : null;
}
function toEpochSeconds(value: string | undefined | null): number | undefined {
if (!value) return undefined;
const ts = Date.parse(value);
if (Number.isNaN(ts)) return undefined;
return Math.floor(ts / 1000);
}
function formatDate(value: string | undefined | null): string {
if (!value) return '';
const date = new Date(value);
if (Number.isNaN(date.getTime())) return '';
return date.toLocaleDateString();
}
function mapEntryToCard(entry: MapDetailWithOrder): PlaylistSongCard | null {
const rawMap = (entry as unknown as { map?: MapDetail }).map ?? (entry as unknown as MapDetail);
if (!rawMap) return null;
const versions = rawMap.versions ?? [];
const version = getPublishedVersion(rawMap) ?? versions[0] ?? null;
const diff = version ? getPrimaryDifficulty(version) : null;
const published = rawMap.lastPublishedAt ?? rawMap.createdAt ?? rawMap.updatedAt ?? version?.createdAt ?? null;
const hash = version?.hash ?? rawMap.id ?? rawMap.hash ?? null;
if (!hash) return null;
const beatsaverKey = version?.key ?? rawMap.id ?? undefined;
const coverURL = version?.coverURL ?? rawMap.coverURL ?? undefined;
const diffName = diff?.difficulty ?? 'Unknown';
const modeName = diff?.characteristic ?? 'Standard';
return {
id: rawMap.id ?? hash,
hash,
coverURL,
songName: rawMap.name,
mapper: rawMap.uploader?.name ?? undefined,
timeset: toEpochSeconds(published),
diffName,
modeName,
beatsaverKey,
publishedLabel: formatDate(published),
score: typeof rawMap.stats?.score === 'number' ? rawMap.stats.score : null
};
}
function isFiniteScore(value: number | undefined | null): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
function playlistLink(id: number | string | undefined): string {
if (id === undefined || id === null) return playlistBaseUrl;
return `${playlistBaseUrl}${id}`;
}
function profileLink(id: number | string | undefined): string {
if (id === undefined || id === null) return profileBaseUrl;
return `${profileBaseUrl}${id}#playlists`;
}
function sanitizeDescription(value: string | null | undefined): string {
if (!value) return '';
return value.replace(/[^a-zA-Z0-9 ]+/g, ' ').replace(/\s+/g, ' ').trim();
}
function truncateTitle(value: string | null | undefined, maxLength = 20): string {
if (!value) return '';
if (value.length <= maxLength) return value;
const sliced = value.slice(0, maxLength - 1).trimEnd();
return `${sliced}…`;
}
</script>
<section class="py-8">
<h1 class="font-display text-3xl sm:text-4xl">Playlist Discovery</h1>
<p class="mt-2 text-muted max-w-2xl">
See <strong><a href="https://bsaber.com/playlists" target="_blank" rel="noreferrer">Featured Packs</a> on Beast Saber</strong> for curated map packs. You can also view most packs by searching BeatSaver for <a href="https://beatsaver.com/playlists?q=picks&order=Latest" target="_blank" rel="noreferrer">picks</a> or <a href="https://beatsaver.com/playlists?q=pack&verified=true&order=Latest" target="_blank" rel="noreferrer">packs</a>.
Otherwise this page is a UI/UX experiment that shows playlists by verified mappers, and provides a reactive interface for previewing map ratings and listening to song previews.
</p>
<HasToolAccess player={data?.player ?? null} requirement={requirement} adminRank={data?.adminRank ?? null} adminPlayer={data?.adminPlayer ?? null}>
{#if data?.error}
<div class="mt-6 rounded-md border border-danger/40 bg-danger/10 px-4 py-3 text-danger text-sm">
{data.error}
</div>
{/if}
{#if !data?.error && playlists.length === 0}
<div class="mt-6 text-muted">No playlists found for this page.</div>
{/if}
{#if playlists.length > 0}
<div class="mt-6 flex flex-wrap items-center gap-3 text-sm text-muted">
<span>Page {page} {#if totalPages}of {totalPages}{/if}</span>
{#if total != null}
<span>({total.toLocaleString()} total playlists)</span>
{/if}
</div>
<div class="mt-6 playlists-grid">
{#each playlists as playlist (playlist.playlistId)}
{@const displayName = truncateTitle(playlist.name)}
{@const description = sanitizeDescription(playlist.description ?? '')}
<article class:expanded={Boolean(expanded[playlist.playlistId])} class="playlist-tile card-surface">
<button class="tile-header" type="button" on:click={() => togglePlaylist(playlist.playlistId)}>
<div class="tile-cover">
<img src={playlist.playlistImage} alt={`Playlist cover for ${playlist.name}`} loading="lazy" />
</div>
<div class="tile-main">
<div class="tile-title">
<a
href={playlistLink(playlist.playlistId)}
target="_blank"
rel="noopener noreferrer"
on:click|stopPropagation
title={playlist.name}
>
{displayName}
</a>
<span class="map-count">{playlist.stats?.totalMaps ?? 0} maps</span>
</div>
{#if isFiniteScore(playlist.stats?.avgScore)}
<div class="tile-score">
<ScoreBar value={playlist.stats?.avgScore ?? null} size="sm" />
</div>
{/if}
<div class="tile-sub">
<span>
by
{#if playlist.owner?.name}
<a href={profileLink(playlist.owner.id)} target="_blank" rel="noopener noreferrer" on:click|stopPropagation>
{playlist.owner.name}
</a>
{:else}
Unknown curator
{/if}
</span>
</div>
</div>
<div class:arrow-expanded={Boolean(expanded[playlist.playlistId])} class="tile-arrow" aria-hidden="true">
<svg viewBox="0 0 24 24" width="20" height="20" role="presentation">
<path d="M6 9l6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
</svg>
</div>
</button>
{#if expanded[playlist.playlistId]}
{@const state = playlistState[playlist.playlistId]}
{@const offset = state?.offset ?? 0}
{@const total = typeof state?.total === 'number' ? state.total : null}
{@const currentCount = state?.maps?.length ?? 0}
{@const atFirstPage = offset <= 0}
{@const atLastPage = total !== null
? (offset + currentCount) >= total
: currentCount < SONGS_PER_PAGE}
<div class="tile-body">
{#if description}
<div class="tile-description">{description}</div>
{/if}
{#if state?.loading}
<div class="tile-status">Loading songs…</div>
{:else if state?.error}
<div class="tile-status error">{state.error}</div>
{:else if state?.maps?.length}
{#if state.total && state.total > SONGS_PER_PAGE}
<div class="tile-pagination">
<button
class="pager-btn"
on:click={() => loadPlaylistMaps(playlist.playlistId, Math.max(0, offset - SONGS_PER_PAGE))}
disabled={state.loading || atFirstPage}
>
Prev {SONGS_PER_PAGE}
</button>
<span class="tile-status">
{#if state.total === 0}
No songs
{:else}
Showing {(state.offset ?? 0) + 1}
-
{Math.min(
(state.offset ?? 0) + state.maps.length,
state.total ?? 0
)}
of {state.total}
{/if}
</span>
<button
class="pager-btn"
on:click={() => loadPlaylistMaps(playlist.playlistId, offset + SONGS_PER_PAGE)}
disabled={state.loading || atLastPage}
>
Next {SONGS_PER_PAGE}
</button>
</div>
{/if}
<div class="songs-grid">
{#each state.maps as card (card.id)}
<MapCard
hash={card.hash}
coverURL={card.coverURL}
songName={card.songName}
mapper={card.mapper}
timeset={card.timeset}
diffName={card.diffName}
modeName={card.modeName}
beatsaverKey={card.beatsaverKey}
compact={true}
showActions={false}
showPublished={false}
>
<ScoreBar
slot="meta-leading"
value={card.score ?? null}
size="sm"
decimals={1}
showLabel={true}
emptyLabel="No score"
/>
</MapCard>
{/each}
</div>
{:else}
<div class="tile-status">No songs found.</div>
{/if}
</div>
{/if}
</article>
{/each}
</div>
<div class="mt-8 flex items-center justify-center gap-3">
<a class="pager-btn" href={prevHref} aria-disabled={!hasPrev} data-disabled={!hasPrev}>
Prev
</a>
<span class="text-sm text-muted">Page {page}{#if totalPages} / {totalPages}{/if}</span>
<a class="pager-btn" href={nextHref} aria-disabled={!hasNext} data-disabled={!hasNext}>
Next
</a>
</div>
{/if}
</HasToolAccess>
</section>
<style>
.playlists-grid {
display: grid;
gap: 1.25rem;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
}
.playlist-tile {
display: flex;
flex-direction: column;
overflow: hidden;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.playlist-tile.expanded {
grid-column: 1 / -1;
}
.tile-header {
width: 100%;
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 1rem;
padding: 1rem 1.25rem 0.85rem;
background: transparent;
color: inherit;
border: none;
cursor: pointer;
text-align: left;
}
.tile-cover {
position: relative;
width: 88px;
height: 88px;
border-radius: 0.6rem;
overflow: hidden;
background: rgba(15, 23, 42, 0.6);
}
.tile-cover img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.tile-main {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.tile-title {
display: flex;
flex-direction: column;
gap: 0.45rem;
}
.tile-title a {
color: white;
font-size: 1.05rem;
font-weight: 600;
text-decoration: none;
}
.tile-title a:hover {
text-decoration: underline;
}
.map-count {
font-size: 0.85rem;
color: rgba(148, 163, 184, 0.85);
}
.tile-score {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.tile-score :global(.score-meter) {
width: 100%;
max-width: 280px;
}
.tile-sub {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
font-size: 0.9rem;
color: rgba(148, 163, 184, 0.95);
}
.tile-sub a {
color: var(--color-neon);
text-decoration: none;
}
.tile-sub a:hover {
text-decoration: underline;
color: color-mix(in srgb, var(--color-neon) 80%, white 20%);
}
.tile-arrow {
align-self: center;
justify-self: center;
color: rgba(148, 163, 184, 0.75);
transition: transform 0.2s ease, color 0.2s ease;
}
.tile-arrow.arrow-expanded {
transform: rotate(180deg);
color: var(--color-neon);
}
.tile-body {
border-top: 1px solid rgba(148, 163, 184, 0.08);
padding: 1rem 1.25rem 1.25rem;
}
.tile-description {
font-size: 0.95rem;
line-height: 1.45;
color: rgba(226, 232, 240, 0.85);
background: rgba(15, 23, 42, 0.55);
padding: 0.75rem 0.9rem;
border-radius: 0.65rem;
margin-bottom: 0.9rem;
}
.tile-status {
color: rgba(148, 163, 184, 0.95);
font-size: 0.9rem;
}
@media (max-width: 640px) {
.tile-header {
grid-template-columns: minmax(64px, 1fr);
grid-template-rows: auto auto;
justify-items: stretch;
}
.tile-cover {
width: 100%;
height: auto;
aspect-ratio: 16 / 9;
}
.tile-arrow {
justify-self: end;
}
}
.tile-status.error {
color: #f87171;
}
.tile-pagination {
margin-bottom: 0.5rem;
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
.songs-grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (min-width: 960px) {
.songs-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
@media (min-width: 1600px) {
.songs-grid {
grid-template-columns: repeat(6, minmax(0, 1fr));
}
}
.pager-btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.4rem 1.1rem;
border-radius: 0.375rem;
border: 1px solid rgba(148, 163, 184, 0.2);
color: white;
font-size: 0.9rem;
text-decoration: none;
transition: all 0.2s ease;
}
.pager-btn:hover {
border-color: rgba(94, 234, 212, 0.5);
box-shadow: 0 0 12px rgba(94, 234, 212, 0.2);
}
.pager-btn[data-disabled='true'] {
opacity: 0.45;
pointer-events: none;
}
.pager-btn:disabled,
.pager-btn:disabled:hover {
opacity: 0.45;
pointer-events: none;
border-color: rgba(148, 163, 184, 0.2);
box-shadow: none;
cursor: default;
}
.card-surface {
background: rgba(15, 23, 42, 0.4);
border: 1px solid rgba(148, 163, 184, 0.08);
border-radius: 0.75rem;
overflow: hidden;
}
.text-danger {
color: #f87171;
}
.bg-danger\/10 {
background-color: rgba(248, 113, 113, 0.1);
}
.border-danger\/40 {
border-color: rgba(248, 113, 113, 0.4);
}
</style>

View File

@ -0,0 +1,37 @@
import { createBeatSaverAPI, type MapDetailWithOrder, type PlaylistPage } from '$lib/server/beatsaver';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
const PAGE_SIZE = 12;
export const GET: RequestHandler = async ({ url, fetch }) => {
const idParam = url.searchParams.get('id');
if (!idParam) {
throw error(400, 'Missing playlist id');
}
const offsetParam = Number.parseInt(url.searchParams.get('offset') ?? '0', 10);
const offset = Number.isFinite(offsetParam) && offsetParam >= 0 ? offsetParam : 0;
const api = createBeatSaverAPI(fetch);
try {
const detail = (await api.getPlaylistDetail(idParam, { page: 0 })) as PlaylistPage;
const maps = Array.isArray(detail?.maps) ? detail.maps : [];
const totalCount = detail?.playlist?.stats?.totalMaps ?? maps.length;
const slice = maps.slice(offset, offset + PAGE_SIZE) as MapDetailWithOrder[];
return json({
playlist: detail?.playlist ?? null,
maps: slice,
offset,
page: Math.floor(offset / PAGE_SIZE),
pageSize: PAGE_SIZE,
totalCount
});
} catch (err) {
console.error('Failed to load playlist detail', idParam, err);
throw error(502, 'Failed to load playlist detail');
}
};