Compare commits

...

16 Commits

25 changed files with 2931 additions and 164 deletions
+2 -2
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`
+40 -5
View File
@@ -24,12 +24,47 @@ npm run dev
npm run dev -- --open
```
## Building
## Nix Deployment
To create a production version of your app:
I use Caddy for TLS.
```sh
npm run build
```
plebsaber.stream {
reverse_proxy http://127.0.0.1:8037
}
```
You can preview the production build with `npm run preview`.
I use sops-nix to deploy the flake with OAuth secrets.
```js
sops = {
defaultSopsFile = ./sops.yaml;
secrets = {
"plebsaber-stream.env" = {
sopsFile = ../_sops/plebsaber-stream.env;
format = "dotenv";
restartUnits = [ "plebsaber-stream.service" ];
};
}
};
services.plebsaber-stream = {
enable = true;
environmentFile = config.sops.secrets."plebsaber-stream.env".path;
};
```
Then add the flake from this repository into your flake inputs.
```js
inputs.plebsaber-stream = {
url = "git+https://git.plebsaber.stream/pleb/plebsaber.stream.git";
inputs.nixpkgs.follows = "nixpkgs";
};
```
For updates, push commits to a repository and then update your flake.
```sh
nix flake lock --update-input plebsaber-stream
nixos-rebuild test .#webserver
```
+1 -1
View File
@@ -7,7 +7,7 @@
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"start": "PORT=8037 node build/index.js",
"start": "HOST=127.0.0.1 PORT=8037 node build/index.js",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
+65
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;
@@ -46,3 +58,56 @@ body {
@utility neon-text {
@apply text-transparent bg-clip-text bg-gradient-to-r from-neon via-accent to-neon-fuchsia;
}
input[type='checkbox'] {
appearance: none;
width: 1.05rem;
height: 1.05rem;
border-radius: 0.35rem;
border: 1px solid rgba(148, 163, 184, 0.35);
background-color: rgba(15, 23, 42, 0.85);
display: grid;
place-content: center;
transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease, transform 0.2s ease;
cursor: pointer;
}
input[type='checkbox']::after {
content: '';
width: 0.55rem;
height: 0.55rem;
clip-path: polygon(14% 44%, 0 60%, 43% 100%, 100% 16%, 86% 0, 40% 64%);
background-color: transparent;
transform: scale(0.4) rotate(6deg);
opacity: 0;
transition: opacity 0.12s ease, transform 0.12s ease, background-color 0.12s ease;
}
input[type='checkbox']:hover {
border-color: rgba(94, 234, 212, 0.4);
}
input[type='checkbox']:focus-visible {
outline: none;
border-color: rgba(94, 234, 212, 0.6);
box-shadow: 0 0 0 2px rgba(94, 234, 212, 0.25);
}
input[type='checkbox']:checked {
border-color: rgba(34, 211, 238, 0.8);
background-color: rgba(34, 211, 238, 0.18);
box-shadow: 0 0 0 2px rgba(34, 211, 238, 0.2);
}
input[type='checkbox']:checked::after {
background-color: var(--color-neon);
opacity: 1;
transform: scale(1) rotate(0deg);
}
input[type='checkbox']:disabled {
cursor: not-allowed;
opacity: 0.55;
box-shadow: none;
border-color: rgba(148, 163, 184, 0.2);
}
+544
View File
@@ -0,0 +1,544 @@
<script lang="ts">
import { onMount } from 'svelte';
import PlayerCard from '$lib/components/PlayerCard.svelte';
type GuestbookAuthor = {
beatleaderId: string;
name: string | null;
avatar: string | null;
country: string | null;
rank: number | null;
techPp: number | null;
accPp: number | null;
passPp: number | null;
};
type GuestbookComment = {
id: string;
message: string;
author: GuestbookAuthor;
createdAt: number;
updatedAt: number | null;
};
type GuestbookViewer = {
beatleaderId: string;
name: string | null;
avatar: string | null;
};
type GuestbookPagination = {
total: number;
offset: number;
limit: number;
hasPrev: boolean;
hasNext: boolean;
};
type GuestbookResponse = {
viewer: GuestbookViewer | null;
comments: GuestbookComment[];
pagination?: GuestbookPagination | null;
};
let loading = false;
let error: string | null = null;
let comments: GuestbookComment[] = [];
let viewer: GuestbookViewer | null = null;
let newMessage = '';
let newMessageError: string | null = null;
let submittingNew = false;
let pagination: GuestbookPagination = { total: 0, offset: 0, limit: 5, hasPrev: false, hasNext: false };
const loginUrl = '/auth/beatleader/login';
const PAGE_SIZE = 5;
$: showingStart = pagination.total > 0 ? pagination.offset + 1 : 0;
$: showingEnd = pagination.total > 0 ? Math.min(pagination.offset + comments.length, pagination.total) : 0;
function normalizePagination(data: GuestbookResponse, fallbackOffset: number): GuestbookPagination {
const page = data.pagination ?? null;
const limit = typeof page?.limit === 'number' && Number.isFinite(page.limit) && page.limit > 0 ? page.limit : PAGE_SIZE;
const total = typeof page?.total === 'number' && page.total >= 0 ? page.total : Math.max(data.comments.length + fallbackOffset, 0);
const offset = typeof page?.offset === 'number' && page.offset >= 0 ? page.offset : fallbackOffset;
const hasPrev = page?.hasPrev ?? offset > 0;
const hasNext = page?.hasNext ?? offset + data.comments.length < total;
return { total, offset, limit, hasPrev, hasNext };
}
function formatTimestamp(ts: number): string {
const now = Date.now();
const diff = Math.max(0, now - ts);
const minute = 60 * 1000;
const hour = 60 * minute;
const day = 24 * hour;
const week = 7 * day;
const month = 30 * day;
const year = 365 * day;
if (diff < minute) {
const seconds = Math.floor(diff / 1000);
return seconds <= 1 ? 'just now' : `${seconds} seconds ago`;
}
if (diff < hour) {
const minutes = Math.floor(diff / minute);
return minutes === 1 ? 'a minute ago' : `${minutes} minutes ago`;
}
if (diff < day) {
const hours = Math.floor(diff / hour);
return hours === 1 ? 'an hour ago' : `${hours} hours ago`;
}
if (diff < week) {
const days = Math.floor(diff / day);
return days === 1 ? 'yesterday' : `${days} days ago`;
}
if (diff < month) {
const weeks = Math.floor(diff / week);
return weeks === 1 ? 'a week ago' : `${weeks} weeks ago`;
}
if (diff < year) {
const months = Math.floor(diff / month);
return months === 1 ? 'a month ago' : `${months} months ago`;
}
const years = Math.floor(diff / year);
return years === 1 ? 'a year ago' : `${years} years ago`;
}
async function fetchGuestbook(offset = 0): Promise<void> {
loading = true;
error = null;
try {
const params = new URLSearchParams({
limit: String(PAGE_SIZE),
offset: String(Math.max(0, Math.floor(offset)))
});
const res = await fetch(`/api/guestbook?${params.toString()}`);
if (!res.ok) {
const body = await res.json().catch(() => null);
const message = body?.error ?? `Failed to load guestbook (${res.status})`;
throw new Error(message);
}
const data = (await res.json()) as GuestbookResponse;
viewer = data.viewer ?? null;
comments = Array.isArray(data.comments) ? data.comments : [];
pagination = normalizePagination(data, Math.max(0, offset));
} catch (err) {
error = err instanceof Error ? err.message : 'Failed to load guestbook.';
} finally {
loading = false;
}
}
async function postComment(message: string): Promise<void> {
const res = await fetch('/api/guestbook', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ message })
});
const payload = await res.json().catch(() => null);
if (!res.ok) {
const messageText = payload?.error ?? `Request failed (${res.status})`;
throw new Error(messageText);
}
const data = payload as GuestbookResponse;
viewer = data.viewer ?? viewer;
comments = Array.isArray(data.comments) ? data.comments : comments;
pagination = normalizePagination(data, 0);
}
async function deleteComment(id: string): Promise<void> {
const params = new URLSearchParams({
id,
limit: String(PAGE_SIZE),
offset: String(pagination.offset)
});
const res = await fetch(`/api/guestbook?${params.toString()}`, {
method: 'DELETE'
});
const payload = await res.json().catch(() => null);
if (!res.ok) {
const messageText = payload?.error ?? `Failed to delete comment (${res.status})`;
throw new Error(messageText);
}
const data = payload as GuestbookResponse;
comments = Array.isArray(data.comments) ? data.comments : comments;
pagination = normalizePagination(data, pagination.offset);
}
async function submitNewComment(): Promise<void> {
if (!viewer) {
newMessageError = 'You must be logged in to leave a comment.';
return;
}
const trimmed = newMessage.trim();
if (!trimmed) {
newMessageError = 'Please enter a message before submitting.';
return;
}
if (trimmed.length > 2000) {
newMessageError = 'Message exceeds the 2000 character limit.';
return;
}
submittingNew = true;
newMessageError = null;
try {
await postComment(trimmed);
newMessage = '';
} catch (err) {
newMessageError = err instanceof Error ? err.message : 'Failed to post comment.';
} finally {
submittingNew = false;
}
}
async function loadNewer(): Promise<void> {
if (loading || !pagination.hasPrev) return;
const nextOffset = Math.max(0, pagination.offset - pagination.limit);
await fetchGuestbook(nextOffset);
}
async function loadOlder(): Promise<void> {
if (loading || !pagination.hasNext) return;
const nextOffset = pagination.offset + pagination.limit;
await fetchGuestbook(nextOffset);
}
onMount(() => {
void fetchGuestbook(0);
});
</script>
<section class="guestbook-section">
<div class="guestbook-header">
<h2 class="font-display tracking-widest">Guestbook</h2>
</div>
{#if viewer}
<form class="guestbook-form" on:submit|preventDefault={submitNewComment}>
<textarea
id="guestbook-new-message"
class="input"
bind:value={newMessage}
maxlength={2000}
rows={4}
placeholder="Leave your markdrop a note in the guestbook!"
></textarea>
{#if newMessageError}
<div class="form-error">{newMessageError}</div>
{/if}
<div class="form-actions">
<button class="btn-neon" type="submit" disabled={submittingNew}>
{submittingNew ? 'Posting…' : 'Post Comment'}
</button>
</div>
</form>
{:else}
<div class="guestbook-login">
<p>
<a class="underline" href={loginUrl}>Log in with BeatLeader</a> to leave a comment.
</p>
</div>
{/if}
{#if loading}
<div class="guestbook-status">Loading comments…</div>
{:else if error}
<div class="guestbook-error">{error}</div>
{:else if comments.length === 0}
<div class="guestbook-empty">No comments yet. Be the first to say hello!</div>
{:else}
<ul class="guestbook-threads">
{#each comments as comment (comment.id)}
<li class="guestbook-thread">
<article class="guestbook-comment">
<div class="comment-header">
<PlayerCard
name={comment.author.name ?? 'Unknown'}
country={comment.author.country}
rank={null}
showRank={false}
avatar={comment.author.avatar}
width="100%"
avatarSize={56}
techPp={comment.author.techPp}
accPp={comment.author.accPp}
passPp={comment.author.passPp}
playerId={comment.author.beatleaderId}
gradientId={`guestbook-${comment.id}`}
/>
</div>
<p class="comment-body">{comment.message}</p>
<div class="comment-meta">
<div class="comment-meta-left">
{#if viewer?.beatleaderId === comment.author.beatleaderId}
<button
class="comment-delete"
type="button"
on:click={async () => {
try {
await deleteComment(comment.id);
} catch (err) {
console.error(err);
error = err instanceof Error ? err.message : 'Failed to delete comment.';
}
}}
disabled={loading}
>
Delete
</button>
{/if}
</div>
<span class="comment-meta-right">{formatTimestamp(comment.createdAt)}</span>
</div>
</article>
</li>
{/each}
</ul>
{/if}
<div class="guestbook-pagination">
<span class="guestbook-range">
{#if pagination.total > 0}
Showing {showingStart}{showingEnd} of {pagination.total}
{:else}
No comments yet
{/if}
</span>
<div class="guestbook-pagination-buttons">
<button
class="guestbook-nav-button"
type="button"
on:click={loadNewer}
disabled={loading || !pagination.hasPrev}
>
Newer
</button>
<button
class="guestbook-nav-button"
type="button"
on:click={loadOlder}
disabled={loading || !pagination.hasNext}
>
Older
</button>
</div>
</div>
</section>
<style>
.guestbook-section {
border-radius: 1rem;
padding: 0.625rem;
background: linear-gradient(160deg, rgba(15, 23, 42, 0.85), rgba(4, 7, 17, 0.9));
border: 1px solid rgba(148, 163, 184, 0.08);
box-shadow: 0 20px 45px rgba(2, 6, 23, 0.35);
}
.guestbook-header {
margin-bottom: 1.5rem;
}
.guestbook-form {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-bottom: 2rem;
width: 100%;
}
.input {
width: 100%;
border-radius: 0.75rem;
padding: 0.85rem 1rem;
border: 1px solid rgba(148, 163, 184, 0.15);
background: rgba(15, 23, 42, 0.6);
color: rgba(226, 232, 240, 0.95);
resize: vertical;
min-height: 120px;
}
.input:focus {
outline: none;
border-color: rgba(34, 211, 238, 0.45);
box-shadow: 0 0 0 2px rgba(34, 211, 238, 0.15);
}
.form-error {
color: rgba(248, 113, 113, 0.9);
font-size: 0.8rem;
}
.form-actions {
display: flex;
gap: 0.75rem;
align-items: center;
justify-content: flex-end;
}
.guestbook-login {
padding: 1rem 1.25rem;
border-radius: 0.75rem;
border: 1px dashed rgba(148, 163, 184, 0.25);
background: rgba(15, 23, 42, 0.4);
color: rgba(148, 163, 184, 0.9);
margin-bottom: 2rem;
}
.guestbook-status,
.guestbook-error,
.guestbook-empty {
font-size: 0.95rem;
color: rgba(148, 163, 184, 0.85);
padding: 1rem 0;
}
.guestbook-error {
color: rgba(248, 113, 113, 0.9);
}
.guestbook-threads {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.guestbook-thread {
display: flex;
flex-direction: column;
gap: 1rem;
}
.guestbook-comment {
border: 1px solid rgba(148, 163, 184, 0.12);
border-radius: 1rem;
padding: 1.25rem;
background: rgba(8, 12, 24, 0.65);
backdrop-filter: blur(8px);
display: grid;
grid-template-rows: auto 1fr auto;
gap: 0.9rem;
}
.comment-header {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.comment-meta {
font-size: 0.75rem;
color: rgba(148, 163, 184, 0.7);
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.75rem;
}
.comment-meta-left {
display: flex;
align-items: center;
gap: 0.5rem;
}
.comment-meta-right {
display: inline-flex;
align-items: center;
justify-content: flex-end;
min-width: 6rem;
text-align: right;
}
.comment-delete {
background: none;
border: none;
color: rgba(248, 113, 113, 0.85);
font-size: 0.7rem;
text-transform: uppercase;
letter-spacing: 0.08em;
cursor: pointer;
padding: 0.25rem 0;
}
.comment-delete:hover:not(:disabled) {
color: rgba(248, 113, 113, 1);
}
.comment-delete:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.comment-body {
font-size: 0.95rem;
line-height: 1.5;
color: rgba(226, 232, 240, 0.92);
white-space: pre-wrap;
}
.guestbook-pagination {
margin-top: 1.75rem;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
}
.guestbook-range {
font-size: 0.8rem;
color: rgba(148, 163, 184, 0.75);
letter-spacing: 0.04em;
}
.guestbook-pagination-buttons {
display: flex;
gap: 0.5rem;
}
.guestbook-nav-button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.5rem 0.95rem;
border-radius: 9999px;
border: 1px solid rgba(148, 163, 184, 0.25);
background: rgba(15, 23, 42, 0.55);
color: rgba(226, 232, 240, 0.88);
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.08em;
transition: border-color 0.2s ease, color 0.2s ease, background 0.2s ease;
}
.guestbook-nav-button:hover:not(:disabled) {
border-color: rgba(34, 211, 238, 0.45);
color: rgba(34, 211, 238, 0.95);
background: rgba(15, 23, 42, 0.7);
}
.guestbook-nav-button:disabled {
opacity: 0.45;
cursor: not-allowed;
}
@media (max-width: 640px) {
.guestbook-section {
padding: 1.75rem;
}
.comment-meta {
font-size: 0.7rem;
}
}
</style>
+1 -1
View File
@@ -62,7 +62,7 @@
: `https://beatsaver.com/search/hash/${hash}`;
</script>
<div class="flex flex-wrap gap-2">
<div class="map-action-buttons flex flex-wrap gap-2">
<a
class="rounded-md border border-white/10 px-2 py-1 text-xs hover:border-white/20"
href={beatLeaderUrl}
+160 -19
View File
@@ -2,6 +2,7 @@
import DifficultyLabel from './DifficultyLabel.svelte';
import MapActionButtons from './MapActionButtons.svelte';
import SongPlayer from './SongPlayer.svelte';
import ScoreBar from './ScoreBar.svelte';
// Song metadata
export let hash: string;
@@ -18,48 +19,57 @@
// BeatLeader/BeatSaver links
export let leaderboardId: string | undefined = undefined;
export let beatsaverKey: string | undefined = undefined;
// BeatSaver stats
export let score: number | undefined = undefined;
export let showActions = true;
export let showPublished = true;
$: hasScore = typeof score === 'number' && Number.isFinite(score);
</script>
<div class="aspect-square bg-black/30">
<div class="card-wrapper">
<div 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 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="meta">
<div class="meta-leading">
<slot name="meta-leading">
<DifficultyLabel {diffName} {modeName} />
<div class="flex-1">
<SongPlayer {hash} preferBeatLeader={true} />
</slot>
{#if hasScore}
<ScoreBar value={score} showLabel={true} size="sm" decimals={1} className="score-meter--with-max" />
{/if}
</div>
</div>
<slot name="content" />
<div class="mt-3">
{#if showActions}
<div class="actions">
<MapActionButtons
{hash}
{leaderboardId}
@@ -67,6 +77,137 @@
{modeName}
{beatsaverKey}
/>
<div class="player">
<SongPlayer {hash} preferBeatLeader={true} />
</div>
</div>
{/if}
</div>
</div>
<style>
.card-wrapper {
display: flex;
flex-direction: column;
gap: 0.75rem;
width: 100%;
}
.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;
}
.body {
padding: 0.75rem 0.75rem 1rem;
display: flex;
flex-direction: column;
flex: 1;
}
.title {
font-weight: 600;
font-size: 1rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.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 :global(.score-meter) {
width: 100%;
max-width: 45%;
margin-left: auto;
}
.actions {
margin-top: 0.6rem;
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
}
.player {
flex: 1;
max-width: 45%;
margin-left: auto;
}
.actions :global(.map-action-buttons) {
display: inline-flex;
flex-wrap: wrap;
gap: 0.5rem;
}
@media (max-width: 959px) {
.player {
max-width: none;
width: 100%;
margin-left: 0;
}
}
:global(.difficulty-label) {
white-space: nowrap;
}
</style>
+4 -14
View File
@@ -2,7 +2,7 @@
import { onMount } from 'svelte';
import { browser } from '$app/environment';
import PlayerCard from '$lib/components/PlayerCard.svelte';
import type { BeatLeaderPlayerProfile } from '$lib/utils/plebsaber-utils';
import { fetchBeatLeaderPlayerProfile, type BeatLeaderPlayerProfile } from '$lib/utils/plebsaber-utils';
export let playerA = '';
export let playerB = '';
@@ -69,23 +69,13 @@
history.replaceState(null, '', url);
}
async function fetchPlayerProfile(playerId: string): Promise<BeatLeaderPlayerProfile | null> {
try {
const res = await fetch(`https://api.beatleader.xyz/player/${encodeURIComponent(playerId)}`);
if (!res.ok) return null;
return (await res.json()) as BeatLeaderPlayerProfile;
} catch {
return null;
}
}
async function loadDefaultPlayerCards(a: string, b: string): Promise<void> {
playerAProfile = null;
playerBProfile = null;
if (!a || !b) return;
const [pa, pb] = await Promise.all([
fetchPlayerProfile(a),
fetchPlayerProfile(b)
fetchBeatLeaderPlayerProfile(a),
fetchBeatLeaderPlayerProfile(b)
]);
playerAProfile = pa;
playerBProfile = pb;
@@ -110,7 +100,7 @@
}
try {
const profile = await fetchPlayerProfile(trimmed);
const profile = await fetchBeatLeaderPlayerProfile(trimmed);
// Only update if this is still the current player ID
const currentId = player === 'A' ? playerA.trim() : playerB.trim();
if (currentId === trimmed) {
+117
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>
+279 -20
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);
}
+130
View File
@@ -0,0 +1,130 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import { randomUUID } from 'node:crypto';
export type GuestbookAuthor = {
beatleaderId: string;
name: string | null;
avatar: string | null;
country: string | null;
rank: number | null;
techPp: number | null;
accPp: number | null;
passPp: number | null;
};
export type GuestbookComment = {
id: string;
message: string;
author: GuestbookAuthor;
createdAt: number;
updatedAt: number | null;
};
type GuestbookFileData = {
comments: GuestbookComment[];
};
const DATA_DIR = '.data';
const GUESTBOOK_FILE = 'guestbook.json';
const EMPTY_DATA: GuestbookFileData = { comments: [] };
const CONTROL_CHARS_REGEX = /[\u0000-\u001F\u007F]/g;
const HTML_TAG_REGEX = /<[^>]*>/g;
const JAVASCRIPT_PROTOCOL_REGEX = /javascript:/gi;
function sanitizeGuestbookMessage(value: string): string {
if (!value) return '';
const withoutTags = value.replace(HTML_TAG_REGEX, '');
const withoutControl = withoutTags.replace(CONTROL_CHARS_REGEX, ' ');
const withoutJsProtocol = withoutControl.replace(JAVASCRIPT_PROTOCOL_REGEX, '');
return withoutJsProtocol.trim();
}
function ensureDataDir(): void {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
}
}
function resolveGuestbookPath(): string {
return path.join(process.cwd(), DATA_DIR, GUESTBOOK_FILE);
}
function loadGuestbookFile(): GuestbookFileData {
try {
const filePath = resolveGuestbookPath();
if (!fs.existsSync(filePath)) {
return { ...EMPTY_DATA, comments: [] };
}
const raw = fs.readFileSync(filePath, 'utf-8');
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object') {
return { ...EMPTY_DATA, comments: [] };
}
const comments = Array.isArray((parsed as GuestbookFileData).comments)
? ((parsed as GuestbookFileData).comments as GuestbookComment[])
: [];
return { comments };
} catch (error) {
console.error('Failed to read guestbook store', error);
return { ...EMPTY_DATA, comments: [] };
}
}
function persistGuestbookFile(data: GuestbookFileData): void {
try {
ensureDataDir();
fs.writeFileSync(resolveGuestbookPath(), JSON.stringify(data, null, 2), 'utf-8');
} catch (error) {
console.error('Failed to persist guestbook store', error);
}
}
export function listGuestbookComments(): GuestbookComment[] {
const data = loadGuestbookFile();
return [...data.comments]
.map((comment) => ({ ...comment, message: sanitizeGuestbookMessage(comment.message) }))
.sort((a, b) => b.createdAt - a.createdAt);
}
export function addGuestbookComment(input: {
message: string;
author: GuestbookAuthor;
}): GuestbookComment {
const data = loadGuestbookFile();
const sanitizedMessage = sanitizeGuestbookMessage(input.message);
const comment: GuestbookComment = {
id: randomUUID(),
message: sanitizedMessage,
author: input.author,
createdAt: Date.now(),
updatedAt: null
};
data.comments.push(comment);
persistGuestbookFile(data);
return comment;
}
export function getGuestbookComments(): GuestbookComment[] {
return listGuestbookComments();
}
export function deleteGuestbookComment(id: string, requesterBeatleaderId: string): boolean {
if (!id) return false;
const data = loadGuestbookFile();
const index = data.comments.findIndex(
(comment) => comment.id === id && comment.author.beatleaderId === requesterBeatleaderId
);
if (index === -1) return false;
data.comments.splice(index, 1);
persistGuestbookFile(data);
return true;
}
+32 -2
View File
@@ -11,6 +11,7 @@ export type MapMeta = {
key?: string;
coverURL?: string;
mapper?: string;
score?: number;
};
export type StarInfo = {
@@ -105,7 +106,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;
@@ -179,7 +181,8 @@ export async function fetchBeatSaverMeta(hash: string): Promise<MapMeta | null>
songName: data?.metadata?.songName ?? data?.name ?? undefined,
key: data?.id ?? undefined,
coverURL: cover,
mapper: data?.uploader?.name ?? undefined
mapper: data?.uploader?.name ?? undefined,
score: typeof data?.stats?.score === 'number' ? data.stats.score : undefined
};
} catch {
// Fallback to CDN cover only
@@ -222,6 +225,33 @@ export async function fetchBeatLeaderStarsByHash(
}
}
export async function fetchBeatLeaderPlayerProfile(
playerId: string,
fetcher?: typeof fetch,
authMode: 'steam' | 'oauth' | 'session' | 'auto' | 'none' = 'auto'
): Promise<BeatLeaderPlayerProfile | null> {
const trimmed = playerId?.trim?.();
if (!trimmed) return null;
const callFetch = (fetcher ?? globalThis.fetch) as typeof fetch | undefined;
if (!callFetch) return null;
const search = new URLSearchParams();
if (authMode) {
search.set('auth', authMode);
}
const url = `/api/beatleader/player/${encodeURIComponent(trimmed)}${search.size ? `?${search.toString()}` : ''}`;
try {
const res = await callFetch(url);
if (!res.ok) return null;
return (await res.json()) as BeatLeaderPlayerProfile;
} catch {
return null;
}
}
/**
* Load metadata for a list of items with unique hashes
* Only loads metadata that isn't already in the cache
+19 -5
View File
@@ -1,10 +1,14 @@
<script lang="ts">
import Guestbook from '$lib/components/Guestbook.svelte';
</script>
<section class="grid items-center gap-10 py-12 md:py-20 lg:grid-cols-2">
<div class="space-y-6">
<h1 class="font-display text-4xl sm:text-5xl lg:text-6xl leading-tight">
helper tools for <span class="neon-text">Beat Saber</span>
</h1>
<p class="max-w-prose text-lg text-muted">
Notes about how things work, helpers and utilities.
Notes about how things work and utilities for finding maps to play.
</p>
<div class="flex flex-wrap gap-3">
<a href="/tools" class="btn-neon">Explore Tools</a>
@@ -18,20 +22,26 @@
<div class="grid grid-cols-2 gap-4">
<a href="/tools/compare-histories" class="rounded-lg bg-black/30 ring-1 ring-white/10 p-4 block hover:ring-white/20 transition">
<div class="text-sm text-muted">Tool</div>
<div class="mt-1 text-2xl font-mono">Compare PlayerHistories</div>
<div class="mt-1 text-2xl font-mono">Player History Comparison</div>
<div class="mt-1 text-sm text-muted">A vs B: songs A played that B has not</div>
</a>
<a href="/tools/playlist-discovery" class="rounded-lg bg-black/30 ring-1 ring-white/10 p-4 block hover:ring-white/20 transition">
<div class="text-sm text-muted">Tool</div>
<div class="mt-1 text-2xl font-mono">Playlist Discovery</div>
<div class="mt-1 text-sm text-muted">Experimental UX for browsing new playlists on BeatSaver</div>
</a>
</div>
</div>
</div>
</section>
<section class="py-10">
<section class="py-12">
<div class="grid gap-10 xl:gap-14 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)] items-start">
<div class="space-y-6">
<div class="prose prose-invert max-w-none">
<h2 class="font-display tracking-widest">Latest Guides</h2>
</div>
<div class="not-prose mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div class="not-prose grid gap-4 sm:grid-cols-2 lg:grid-cols-1 xl:grid-cols-2">
<a href="/guides/finding-new-songs" class="card-surface p-5 block">
<div class="text-sm text-muted">Guide</div>
<h3 class="font-semibold mt-1">Finding New Songs (BeatLeader)</h3>
@@ -43,6 +53,10 @@
<p class="mt-1 text-sm text-muted">Connect BeatLeader and enable unranked stars in tools.</p>
</a>
</div>
</div>
<Guestbook />
</div>
</section>
+221
View File
@@ -0,0 +1,221 @@
import type { RequestHandler } from '@sveltejs/kit';
import {
addGuestbookComment,
deleteGuestbookComment,
getGuestbookComments,
type GuestbookAuthor
} from '$lib/server/guestbookStore';
import { getSession } from '$lib/server/sessionStore';
const MAX_COMMENT_LENGTH = 2000;
const PLAYER_ENDPOINT = 'https://api.beatleader.com/player/';
const DEFAULT_PAGE_SIZE = 5;
const MAX_PAGE_SIZE = 50;
type GuestbookViewer = {
beatleaderId: string;
name: string | null;
avatar: string | null;
};
type GuestbookResponse = {
viewer: GuestbookViewer | null;
comments: ReturnType<typeof getGuestbookComments>;
pagination: {
total: number;
offset: number;
limit: number;
hasPrev: boolean;
hasNext: boolean;
};
};
function mapSessionToViewer(session: ReturnType<typeof getSession>): GuestbookViewer | null {
if (!session) return null;
return {
beatleaderId: session.beatleaderId,
name: session.name ?? null,
avatar: session.avatar ?? null
};
}
async function buildAuthor(session: NonNullable<ReturnType<typeof getSession>>, fetchFn: typeof fetch): Promise<GuestbookAuthor> {
const base: GuestbookAuthor = {
beatleaderId: session.beatleaderId,
name: session.name ?? null,
avatar: session.avatar ?? null,
country: null,
rank: null,
techPp: null,
accPp: null,
passPp: null
};
try {
const res = await fetchFn(`${PLAYER_ENDPOINT}${encodeURIComponent(session.beatleaderId)}?stats=true`);
if (!res.ok) return base;
const data = (await res.json()) as Record<string, unknown>;
return {
beatleaderId: session.beatleaderId,
name: typeof data.name === 'string' ? (data.name as string) : base.name,
avatar: typeof data.avatar === 'string' ? (data.avatar as string) : base.avatar,
country: typeof data.country === 'string' ? (data.country as string) : base.country,
rank: typeof data.rank === 'number' ? (data.rank as number) : base.rank,
techPp: typeof data.techPp === 'number' ? (data.techPp as number) : base.techPp,
accPp: typeof data.accPp === 'number' ? (data.accPp as number) : base.accPp,
passPp: typeof data.passPp === 'number' ? (data.passPp as number) : base.passPp
};
} catch (error) {
console.error('Failed to load BeatLeader profile for guestbook author', error);
return base;
}
}
function sanitizeMessage(value: unknown): { ok: true; message: string } | { ok: false; error: string } {
if (typeof value !== 'string') {
return { ok: false, error: 'Message must be a string' };
}
const trimmed = value.trim();
if (!trimmed) {
return { ok: false, error: 'Message cannot be empty' };
}
if (trimmed.length > MAX_COMMENT_LENGTH) {
return { ok: false, error: `Message exceeds ${MAX_COMMENT_LENGTH} characters` };
}
return { ok: true, message: trimmed };
}
function parseLimit(value: string | null): number {
if (!value) return DEFAULT_PAGE_SIZE;
const parsed = Math.floor(Number(value));
if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_PAGE_SIZE;
return Math.min(MAX_PAGE_SIZE, parsed);
}
function parseOffset(value: string | null): number {
if (!value) return 0;
const parsed = Math.floor(Number(value));
if (!Number.isFinite(parsed) || parsed <= 0) return 0;
return parsed;
}
function clampOffset(offset: number, total: number): number {
if (total <= 0) return 0;
const safeOffset = Math.max(0, Math.floor(offset));
const maxOffset = Math.max(0, total - 1);
return Math.min(safeOffset, maxOffset);
}
function buildGuestbookPayload(
session: ReturnType<typeof getSession>,
limit: number,
offset: number
): GuestbookResponse {
const allComments = getGuestbookComments();
const total = allComments.length;
const safeLimit = Math.max(1, Math.min(MAX_PAGE_SIZE, Math.floor(limit)));
const safeOffset = clampOffset(offset, total);
const pageComments = allComments.slice(safeOffset, safeOffset + safeLimit);
return {
viewer: mapSessionToViewer(session),
comments: pageComments,
pagination: {
total,
offset: safeOffset,
limit: safeLimit,
hasPrev: safeOffset > 0,
hasNext: safeOffset + safeLimit < total
}
};
}
function jsonResponse(payload: GuestbookResponse, init?: ResponseInit): Response {
return new Response(JSON.stringify(payload), {
headers: { 'content-type': 'application/json' },
...init
});
}
export const GET: RequestHandler = ({ cookies, url }) => {
const session = getSession(cookies);
const limit = parseLimit(url.searchParams.get('limit'));
const offset = parseOffset(url.searchParams.get('offset'));
return jsonResponse(buildGuestbookPayload(session, limit, offset));
};
export const POST: RequestHandler = async ({ request, cookies, fetch }) => {
const session = getSession(cookies);
if (!session) {
return new Response(
JSON.stringify({ error: 'Unauthorized', login: '/auth/beatleader/login' }),
{ status: 401, headers: { 'content-type': 'application/json' } }
);
}
let body: unknown;
try {
body = await request.json();
} catch {
return new Response(JSON.stringify({ error: 'Invalid JSON body' }), {
status: 400,
headers: { 'content-type': 'application/json' }
});
}
const sanitizedMessage = sanitizeMessage((body as Record<string, unknown>)?.message);
if (!sanitizedMessage.ok) {
return new Response(JSON.stringify({ error: sanitizedMessage.error }), {
status: 400,
headers: { 'content-type': 'application/json' }
});
}
const { message } = sanitizedMessage;
try {
const author = await buildAuthor(session, fetch);
addGuestbookComment({ message, author });
} catch (error) {
const msg = error instanceof Error ? error.message : 'Failed to save comment';
return new Response(JSON.stringify({ error: msg }), {
status: 400,
headers: { 'content-type': 'application/json' }
});
}
return jsonResponse(buildGuestbookPayload(session, DEFAULT_PAGE_SIZE, 0), { status: 201 });
};
export const DELETE: RequestHandler = ({ url, cookies }) => {
const session = getSession(cookies);
if (!session) {
return new Response(
JSON.stringify({ error: 'Unauthorized', login: '/auth/beatleader/login' }),
{ status: 401, headers: { 'content-type': 'application/json' } }
);
}
const id = url.searchParams.get('id') || null;
if (!id) {
return new Response(JSON.stringify({ error: 'Missing comment id' }), {
status: 400,
headers: { 'content-type': 'application/json' }
});
}
const success = deleteGuestbookComment(id, session.beatleaderId);
if (!success) {
return new Response(JSON.stringify({ error: 'Comment not found or not owned by you' }), {
status: 404,
headers: { 'content-type': 'application/json' }
});
}
const limit = parseLimit(url.searchParams.get('limit'));
const offset = parseOffset(url.searchParams.get('offset'));
return jsonResponse(buildGuestbookPayload(session, limit, offset), { status: 200 });
};
+1 -3
View File
@@ -4,15 +4,13 @@
<section class="py-8 prose prose-invert max-w-none">
<h1 class="font-display tracking-widest">Guides</h1>
<p>Community-written tips and guides for improving your Beat Saber game. Contributions welcome.</p>
<p>The best starting point for reading about Beat Saber is the <a href="https://bsmg.wiki" target="_blank" rel="noreferrer">bsmg.wiki</a>, and then <a href="https://bsaber.com" target="_blank" rel="noreferrer">Beast Saber</a>. This page has some complementary community-written advice for finding maps to play and maps to <code>!bsr</code> your favorite Twitch streamers. Contributions welcome.</p>
<div class="not-prose grid gap-4 sm:grid-cols-2 lg:grid-cols-3 mt-6">
{#if dev}
<a href="/guides/beatleader-auth" class="card-surface p-5 block">
<h3 class="font-semibold">BeatLeader Authentication</h3>
<p class="mt-1 text-sm text-muted">Connect BeatLeader to enhance tools like Compare Players.</p>
</a>
{/if}
<a href="/guides/finding-new-songs" class="card-surface p-5 block">
<h3 class="font-semibold">Finding New Songs (BeatLeader)</h3>
<p class="mt-1 text-sm text-muted">Month-by-month search using unranked stars, tech rating, and friend filters.</p>
@@ -1,7 +1,7 @@
<section class="py-8 prose prose-invert max-w-none">
<h1 class="font-display tracking-widest">Finding New Songs with BeatLeader</h1>
<p>
A fast, repeatable workflow to discover fresh maps using BeatLeaders powerful search. It relies on
A slow, but repeatable workflow to discover fresh maps using BeatLeaders powerful search. This relies on
supporteronly unranked star ratings (<code>ShowAllRatings</code>) and sorts by <strong>techRating</strong> to surface interesting patterns.
</p>
@@ -16,11 +16,11 @@
<h2 id="requirements">Requirements</h2>
<ul>
<li><strong>BeatLeader supporter</strong> role on your BL account (Patreon/tipper/supporter/sponsor).</li>
<li><strong><code>ShowAllRatings</code></strong> enabled on your BL profile. See <a href="/guides/beatleader-auth">BeatLeader Authentication</a> for how to sign in and enable it.</li>
<li><strong><code>ShowAllRatings</code></strong> enabled on your BL profile. Navigate to the Leaderboard section in <a href="https://beatleader.com/settings#leaderboard" target="_blank" rel="noreferrer">Beatleader settings</a> and enable "Show rating for all maps"</li>
</ul>
<h2 id="search-setup">Search setup</h2>
<p>Use the BeatLeader maps search with these filters:</p>
<p>Use the BeatLeader map search with these filters:</p>
<ul>
<li><strong>Date range</strong>: pick a single month (e.g., Dec 1 → Jan 1). Iterate month by month.</li>
<li><strong>Stars</strong>: set a band to control density and overall difficulty (e.g., <strong>810</strong> for fun, <strong>68</strong> for warmups).</li>
+2 -1
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>
@@ -179,7 +179,10 @@
<section class="py-8">
<h1 class="font-display text-3xl sm:text-4xl">Compare Play Histories</h1>
<p class="mt-2 text-muted">Maps Player A has played that Player B hasn't — configurable lookback.</p>
<p class="mt-2 text-muted max-w-2xl">
Maps Player A has played that Player B has not.
This tool can be useful for finding songs to <code>!bsr</code> in Twitch streams, so we can recommend songs that we've played that the streamer has not.
</p>
<HasToolAccess player={playerProfile} requirement={requirement} {adminRank} adminPlayer={adminPlayer}>
<PlayerCompareForm bind:playerA bind:playerB {loading} hasResults={results.length > 0} oncompare={onCompare} currentPlayer={playerProfile}>
@@ -238,6 +241,7 @@
modeName={item.difficulties[0]?.characteristic ?? 'Standard'}
leaderboardId={item.leaderboardId}
beatsaverKey={metaByHash[item.hash]?.key}
score={metaByHash[item.hash]?.score}
/>
</article>
{/each}
@@ -313,7 +313,9 @@
<section class="py-8">
<h1 class="font-display text-3xl sm:text-4xl">Player Head-to-Head</h1>
<p class="mt-2 text-muted">Paginated head-to-head results on the same map and difficulty.</p>
<p class="mt-2 text-muted max-w-2xl">
Compare two players on maps they've both played.
</p>
<HasToolAccess player={playerProfile} requirement={requirement} {adminRank} adminPlayer={adminPlayer}>
<PlayerCompareForm bind:playerA bind:playerB {loading} hasResults={items.length > 0} oncompare={onCompare} currentPlayer={playerProfile} />
@@ -499,6 +501,7 @@
modeName={item.modeName}
leaderboardId={item.leaderboardId}
beatsaverKey={metaByHash[item.hash]?.key}
score={metaByHash[item.hash]?.score}
>
<div slot="content">
<div class="mt-3 grid grid-cols-2 gap-3 neon-surface">
@@ -8,6 +8,7 @@
type BeatLeaderPlayerProfile,
fetchAllPlayerScores,
fetchBeatSaverMeta,
fetchBeatLeaderPlayerProfile,
type MapMeta
} from '$lib/utils/plebsaber-utils';
@@ -154,7 +155,7 @@
loadingPreview = true;
try {
const profile = await fetchPlayerProfile(id);
const profile = await fetchBeatLeaderPlayerProfile(id);
// Only update if this is still the current player ID
if (playerId.trim() === id) {
previewPlayerProfile = profile;
@@ -330,16 +331,6 @@
URL.revokeObjectURL(url);
}
async function fetchPlayerProfile(id: string): Promise<BeatLeaderPlayerProfile | null> {
try {
const res = await fetch(`https://api.beatleader.xyz/player/${encodeURIComponent(id)}`);
if (!res.ok) return null;
return (await res.json()) as BeatLeaderPlayerProfile;
} catch {
return null;
}
}
async function onAnalyze(ev: SubmitEvent) {
ev.preventDefault();
errorMsg = null;
@@ -359,7 +350,7 @@
try {
const [scores, profile] = await Promise.all([
fetchAllPlayerScores(playerId.trim(), 150),
fetchPlayerProfile(playerId.trim())
fetchBeatLeaderPlayerProfile(playerId.trim())
]);
analyzedPlayerProfile = profile;
hasAnalyzed = true;
@@ -0,0 +1,122 @@
import {
createBeatSaverAPI,
type PlaylistFull,
type PlaylistSearchParams,
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;
}
const SORT_ORDER_VALUES = ['Latest', 'Relevance', 'Curated'] as const;
type SortOrderOption = (typeof SORT_ORDER_VALUES)[number];
const SORT_ORDER_SET = new Set<string>(SORT_ORDER_VALUES);
const DEFAULT_SORT_ORDER: SortOrderOption = 'Latest';
function parseSortOrder(value: string | null): SortOrderOption {
if (!value) return DEFAULT_SORT_ORDER;
const normalized = value.trim();
return SORT_ORDER_SET.has(normalized) ? (normalized as SortOrderOption) : DEFAULT_SORT_ORDER;
}
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;
const hasSubmitted = url.searchParams.has('submitted');
const rawQuery = url.searchParams.get('q') ?? '';
const query = rawQuery.trim();
const rawSortOrder = url.searchParams.get('order') ?? url.searchParams.get('sortOrder');
const sortOrder = parseSortOrder(rawSortOrder);
const curated = url.searchParams.has('curated');
const verified = url.searchParams.has('verified') ? true : hasSubmitted ? false : true;
const searchState = {
submitted: hasSubmitted,
query,
sortOrder,
curated,
verified
};
const searchParams: PlaylistSearchParams = {
page: pageIndex,
sortOrder,
includeEmpty: false
};
if (query) {
searchParams.query = query;
}
if (curated) {
searchParams.curated = true;
}
if (verified) {
searchParams.verified = true;
}
try {
const response = (await api.searchPlaylists({
...searchParams
})) 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,
search: searchState
};
} 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',
search: searchState
};
}
};
@@ -0,0 +1,928 @@
<script lang="ts">
import { tick } from 'svelte';
import HasToolAccess from '$lib/components/HasToolAccess.svelte';
import ScoreBar from '$lib/components/ScoreBar.svelte';
import PlaylistSongCard from './PlaylistSongCard.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';
const SORT_OPTIONS = ['Latest', 'Relevance', 'Curated'] as const;
type SortOrderOption = (typeof SORT_OPTIONS)[number];
type SearchState = {
submitted: boolean;
query: string;
sortOrder: SortOrderOption;
curated: boolean;
verified: boolean;
};
type PlaylistWithStats = PlaylistFull & { stats?: PlaylistFull['stats'] };
type PlaylistSongCardData = {
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: PlaylistSongCardData[];
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;
search: SearchState;
};
const requirement = TOOL_REQUIREMENTS['playlist-discovery'];
const playlistBaseUrl = 'https://beatsaver.com/playlists/';
const profileBaseUrl = 'https://beatsaver.com/profile/';
let searchForm: HTMLFormElement | null = null;
let appliedSearch: SearchState = {
submitted: false,
query: '',
sortOrder: 'Latest',
curated: false,
verified: true
};
let searchQuery = appliedSearch.query;
let sortOrder: SortOrderOption = appliedSearch.sortOrder;
let curated = appliedSearch.curated;
let verified = appliedSearch.verified;
let lastSearchKey = '';
$: appliedSearch = {
submitted: data?.search?.submitted ?? false,
query: data?.search?.query ?? '',
sortOrder: (data?.search?.sortOrder ?? 'Latest') as SortOrderOption,
curated: Boolean(data?.search?.curated),
verified: data?.search?.verified ?? true
};
$: if (data) {
searchQuery = appliedSearch.query;
sortOrder = appliedSearch.sortOrder;
curated = appliedSearch.curated;
verified = appliedSearch.verified;
}
$: 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 ? buildPageHref(page - 1) : null;
$: nextHref = hasNext ? buildPageHref(page + 1) : null;
let expanded: Record<number, boolean> = {};
let playlistState: Record<number, PlaylistState> = {};
$: {
const currentKey = JSON.stringify({
page,
query: appliedSearch.query,
sortOrder: appliedSearch.sortOrder,
curated: appliedSearch.curated,
verified: appliedSearch.verified
});
if (currentKey !== lastSearchKey) {
lastSearchKey = currentKey;
expanded = {};
playlistState = {};
}
}
type PresetKey = 'default' | 'picks' | 'packs';
function buildPageHref(targetPage: number): string {
const params = new URLSearchParams();
params.set('page', String(targetPage));
params.set('submitted', '1');
if (appliedSearch.query) params.set('q', appliedSearch.query);
if (appliedSearch.sortOrder) params.set('order', appliedSearch.sortOrder);
if (appliedSearch.curated) params.set('curated', 'on');
if (appliedSearch.verified) params.set('verified', 'on');
return `?${params.toString()}`;
}
async function submitSearch() {
await tick();
searchForm?.requestSubmit();
}
async function applyPreset(preset: PresetKey) {
switch (preset) {
case 'default':
searchQuery = '';
sortOrder = 'Latest';
curated = false;
verified = true;
break;
case 'picks':
searchQuery = 'picks';
sortOrder = 'Latest';
curated = false;
verified = false;
break;
case 'packs':
searchQuery = 'pack';
sortOrder = 'Latest';
curated = false;
verified = true;
break;
}
await submitSearch();
}
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 PlaylistSongCardData => 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): PlaylistSongCardData | 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">
This page is a UI/UX experiment that shows playlists with a reactive interface for previewing map ratings and listening to song previews.
See <strong><a href="https://bsaber.com/playlists" target="_blank" rel="noreferrer">Featured Packs</a> on Beast Saber</strong> for curated map packs.
</p>
<HasToolAccess player={data?.player ?? null} requirement={requirement} adminRank={data?.adminRank ?? null} adminPlayer={data?.adminPlayer ?? null}>
<form class="search-form card-surface" method="GET" bind:this={searchForm}>
<input type="hidden" name="submitted" value="1" />
<input type="hidden" name="page" value="1" />
<div class="search-grid">
<label class="form-field search-query">
<span class="form-label">Search</span>
<input type="search" name="q" placeholder="Search playlists" bind:value={searchQuery} />
</label>
<label class="form-field sort-field">
<span class="form-label">Sort order</span>
<select name="order" bind:value={sortOrder} on:change={submitSearch}>
{#each SORT_OPTIONS as option}
<option value={option}>{option}</option>
{/each}
</select>
</label>
</div>
<div class="search-filters">
<label class="filter-checkbox">
<input type="checkbox" name="curated" value="on" bind:checked={curated} on:change={submitSearch} />
<span>Curated playlists</span>
</label>
<label class="filter-checkbox">
<input type="checkbox" name="verified" value="on" bind:checked={verified} on:change={submitSearch} />
<span>Playlists from verified mappers</span>
</label>
</div>
<div class="search-actions">
<button class="form-btn primary" type="submit">Search</button>
<div class="preset-group">
<span class="preset-label">Presets:</span>
<button class="form-btn secondary" type="button" on:click={() => applyPreset('packs')}>
Map Packs
</button>
<button class="form-btn secondary" type="button" on:click={() => applyPreset('picks')}>
Picks
</button>
</div>
</div>
</form>
{#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)}
<PlaylistSongCard
hash={card.hash}
coverURL={card.coverURL}
songName={card.songName}
mapper={card.mapper}
beatsaverKey={card.beatsaverKey}
score={card.score ?? null}
/>
{/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>
.search-form {
margin-top: 1.75rem;
width: 100%;
max-width: 600px;
padding: 1.25rem 1.5rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.search-grid {
display: grid;
gap: 1rem;
grid-template-columns: minmax(0, 1fr) auto;
align-items: end;
}
.form-field {
display: flex;
flex-direction: column;
gap: 0.45rem;
}
.form-label {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: rgba(148, 163, 184, 0.75);
}
.search-query {
min-width: 0;
}
.sort-field {
max-width: 10em;
}
.form-field input,
.form-field select {
background: rgba(15, 23, 42, 0.6);
border: 1px solid rgba(148, 163, 184, 0.2);
border-radius: 0.5rem;
padding: 0.55rem 0.75rem;
color: #e2e8f0;
font-size: 0.95rem;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
}
.form-field input::placeholder {
color: rgba(148, 163, 184, 0.6);
}
.form-field input:focus,
.form-field select:focus {
outline: none;
border-color: rgba(94, 234, 212, 0.5);
box-shadow: 0 0 0 2px rgba(94, 234, 212, 0.2);
}
.search-filters {
display: flex;
flex-wrap: wrap;
gap: 0.75rem 1rem;
align-items: stretch;
}
.filter-checkbox {
position: relative;
display: inline-flex;
align-items: center;
font-size: 0.9rem;
color: rgba(226, 232, 240, 0.9);
line-height: 1.45;
padding: 0.55rem 0.9rem 0.55rem 2.35rem;
border: 1px solid rgba(148, 163, 184, 0.2);
border-radius: 0.5rem;
background: rgba(15, 23, 42, 0.6);
transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
cursor: pointer;
}
.filter-checkbox:hover {
border-color: rgba(94, 234, 212, 0.35);
background: rgba(15, 23, 42, 0.7);
}
.filter-checkbox:focus-within {
border-color: rgba(94, 234, 212, 0.5);
box-shadow: 0 0 0 2px rgba(94, 234, 212, 0.2);
}
.filter-checkbox input {
position: absolute;
left: 0.75rem;
top: 50%;
transform: translateY(-50%);
flex-shrink: 0;
}
.filter-checkbox span {
display: inline-block;
}
.search-actions {
display: flex;
flex-wrap: wrap;
gap: 1rem 1.5rem;
align-items: center;
}
.form-btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.5rem 1.25rem;
border-radius: 0.5rem;
border: 1px solid rgba(148, 163, 184, 0.25);
background: rgba(15, 23, 42, 0.5);
color: white;
font-size: 0.9rem;
font-weight: 500;
transition: all 0.2s ease;
cursor: pointer;
}
.form-btn:hover {
border-color: rgba(94, 234, 212, 0.5);
box-shadow: 0 0 12px rgba(94, 234, 212, 0.2);
}
.form-btn.primary {
background: rgba(94, 234, 212, 0.85);
border-color: rgba(94, 234, 212, 0.85);
color: #0f172a;
font-weight: 600;
}
.form-btn.primary:hover {
box-shadow: 0 8px 20px rgba(94, 234, 212, 0.25);
}
.form-btn.secondary {
background: rgba(15, 23, 42, 0.45);
}
.form-btn:disabled {
opacity: 0.45;
cursor: default;
box-shadow: none;
border-color: rgba(148, 163, 184, 0.2);
}
.preset-group {
display: inline-flex;
flex-wrap: wrap;
gap: 0.75rem;
align-items: center;
}
.preset-label {
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 0.08em;
color: rgba(148, 163, 184, 0.75);
}
@media (max-width: 640px) {
.search-form {
padding: 1rem;
}
.search-grid {
grid-template-columns: minmax(0, 1fr);
}
.sort-field {
max-width: none;
}
.search-filters {
flex-direction: column;
align-items: stretch;
}
.search-actions {
flex-direction: column;
align-items: stretch;
gap: 0.9rem;
}
.preset-group {
justify-content: flex-start;
}
}
.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>
@@ -0,0 +1,158 @@
<script lang="ts">
import ScoreBar from '$lib/components/ScoreBar.svelte';
import SongPlayer from '$lib/components/SongPlayer.svelte';
const beatsaverMapBase = 'https://beatsaver.com/maps/';
export let hash: string;
export let coverURL: string | undefined = undefined;
export let songName: string | undefined = undefined;
export let mapper: string | undefined = undefined;
export let beatsaverKey: string | undefined = undefined;
export let score: number | null | undefined = undefined;
$: mapTitle = songName ?? hash;
$: mapLink = beatsaverKey ? `${beatsaverMapBase}${beatsaverKey}` : null;
</script>
<article class="playlist-map-card card-surface">
<div class="cover">
{#if coverURL}
<img src={coverURL} alt={`Cover art for ${mapTitle}`} loading="lazy" />
{:else}
<div class="placeholder" aria-hidden="true">☁️</div>
{/if}
</div>
<div class="content">
<div class="title" title={mapTitle}>
{#if mapLink}
<a href={mapLink} target="_blank" rel="noreferrer noopener">{mapTitle}</a>
{:else}
<span>{mapTitle}</span>
{/if}
</div>
{#if mapper}
<div class="mapper">{mapper}</div>
{/if}
<div class="metrics">
<ScoreBar value={score ?? null} size="sm" decimals={1} showLabel={true} emptyLabel="No score" />
</div>
<div class="player">
<SongPlayer {hash} preferBeatLeader={true} />
</div>
</div>
</article>
<style>
.playlist-map-card {
display: grid;
grid-template-columns: 104px 1fr;
gap: 1rem;
padding: 0.85rem 1rem;
border-radius: 0.75rem;
background: rgba(15, 23, 42, 0.55);
border: 1px solid rgba(148, 163, 184, 0.12);
box-shadow: 0 18px 36px -18px rgba(15, 23, 42, 0.8);
}
.cover {
position: relative;
width: 100%;
padding-top: 100%;
border-radius: 0.65rem;
overflow: hidden;
background: rgba(15, 23, 42, 0.65);
}
.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;
color: rgba(226, 232, 240, 0.8);
}
.content {
display: flex;
flex-direction: column;
gap: 0.65rem;
min-width: 0;
}
.title {
font-weight: 600;
font-size: 1rem;
color: #f8fafc;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.title a {
color: inherit;
text-decoration: none;
}
.title a:hover {
text-decoration: underline;
color: color-mix(in srgb, var(--color-neon) 80%, white 20%);
}
.mapper {
font-size: 0.8rem;
color: rgba(148, 163, 184, 0.85);
}
.metrics {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.metrics :global(.score-meter) {
width: 100%;
max-width: none;
margin: 0;
}
.player {
margin-top: auto;
padding-top: 0.5rem;
}
.player :global(.song-player) {
width: 100%;
}
@media (max-width: 640px) {
.playlist-map-card {
grid-template-columns: minmax(0, 1fr);
padding: 0.75rem;
gap: 0.75rem;
}
.cover {
padding-top: 60%;
border-radius: 0.5rem;
}
.player {
margin-top: 0.25rem;
}
}
</style>
@@ -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');
}
};
+3 -24
View File
@@ -1,6 +1,6 @@
import { error, redirect } from '@sveltejs/kit';
import { getAllSessions, getSession } from '$lib/server/sessionStore';
import { PLEB_BEATLEADER_ID } from '$lib/utils/plebsaber-utils';
import { PLEB_BEATLEADER_ID, fetchBeatLeaderPlayerProfile } from '$lib/utils/plebsaber-utils';
import type { PageServerLoad } from './$types';
type StatsUser = {
@@ -16,28 +16,7 @@ type StatsUser = {
lastSeenIso: string;
};
type BeatLeaderPlayer = {
id: string;
name: string;
avatar?: string;
country?: string;
rank?: number;
techPp?: number;
accPp?: number;
passPp?: number;
};
async function fetchBeatLeaderProfile(playerId: string): Promise<BeatLeaderPlayer | null> {
try {
const response = await fetch(`https://api.beatleader.xyz/player/${playerId}`);
if (!response.ok) return null;
return (await response.json()) as BeatLeaderPlayer;
} catch {
return null;
}
}
export const load: PageServerLoad = async ({ cookies }) => {
export const load: PageServerLoad = async ({ cookies, fetch }) => {
const currentSession = getSession(cookies);
if (!currentSession) {
throw redirect(302, '/auth/beatleader/login?redirect_uri=%2Ftools%2Fstats');
@@ -59,7 +38,7 @@ export const load: PageServerLoad = async ({ cookies }) => {
// Fetch all player profiles in parallel
const userPromises = Array.from(aggregated.values()).map(async ({ session }) => {
const profile = await fetchBeatLeaderProfile(session.beatleaderId);
const profile = await fetchBeatLeaderPlayerProfile(session.beatleaderId, fetch);
return {
beatleaderId: session.beatleaderId,
name: profile?.name ?? session.name,