Expand website and game trackers
Some checks failed
Test and deploy staging / staging (push) Failing after 5m29s

This commit is contained in:
2026-09-25 22:43:04 +00:00
parent f6b34150d4
commit c2ba8febb4
4076 changed files with 97237 additions and 1453 deletions

View File

@@ -1,80 +1,88 @@
import { and, asc, countDistinct, eq, inArray, sql } from 'drizzle-orm';
import { asc, eq } from 'drizzle-orm';
import { db } from '$lib/server/db';
import {
catchEmAllSettings,
pokemonGameEntries,
trackerGames,
trackerItems,
trackerProgress,
userEntries,
userGames
trackerWeaponRanks,
trackerRanks,
trackerChallenges,
trackerChallengeProgress,
osuEntries
} from '$lib/server/db/schema';
import { loadPokemonProgress } from '$lib/server/tracker-progress';
import { challengeProgress, combinedProgress, sumProgress } from '$lib/game-tracker/progress';
import { summarizeGame } from '$lib/game-tracker/mastery';
import { chronologicalPokemon, pokemonRelease } from '$lib/game-tracker/game-art';
import type { PageServerLoad } from './$types';
const obtainable = inArray(pokemonGameEntries.availability, ['catchable', 'evolve', 'breed']);
async function pokemonSummary(userId: string | undefined) {
let gameIds: number[] | null = null;
if (userId) {
const [settings] = await db
.select({ id: catchEmAllSettings.id })
.from(catchEmAllSettings)
.where(eq(catchEmAllSettings.userId, userId));
const selected = await db
.select({ id: userGames.gameId })
.from(userGames)
.where(eq(userGames.userId, userId));
if (settings || selected.length) gameIds = selected.map((row) => row.id);
}
const scope =
gameIds === null ? obtainable : and(obtainable, inArray(pokemonGameEntries.gameId, gameIds));
const [totals] = await db
.select({
entries: sql<number>`count(*)`.mapWith(Number),
species: countDistinct(pokemonGameEntries.pokemonId),
games: countDistinct(pokemonGameEntries.gameId)
})
.from(pokemonGameEntries)
.where(scope);
const [caught] = userId
? await db
.select({
entries: sql<number>`count(*)`.mapWith(Number),
species: countDistinct(pokemonGameEntries.pokemonId)
})
.from(userEntries)
.innerJoin(pokemonGameEntries, eq(pokemonGameEntries.id, userEntries.pokemonGameEntryId))
.where(and(eq(userEntries.userId, userId), scope))
: [{ entries: 0, species: 0 }];
return { totals, caught };
const progress = await loadPokemonProgress(userId);
return {
...progress,
games: chronologicalPokemon(progress.configured ? progress.games : []).map((g) => ({
...g,
releaseYear: pokemonRelease(g.slug).slice(0, 4)
}))
};
}
async function callOfDutySummary(userId: string | undefined) {
const [gamesList, items, progress] = await Promise.all([
db
.select()
.from(trackerGames)
.where(eq(trackerGames.franchise, 'call-of-duty'))
.orderBy(asc(trackerGames.sortOrder)),
db
.select({
id: trackerItems.id,
gameId: trackerItems.gameId,
kind: trackerItems.kind,
name: trackerItems.name,
category: trackerItems.category,
postLaunch: trackerItems.postLaunch
})
.from(trackerItems),
userId
? db
.select({ itemId: trackerProgress.itemId, milestone: trackerProgress.milestone })
.from(trackerProgress)
.where(eq(trackerProgress.userId, userId))
: Promise.resolve([])
]);
const [gamesList, items, progress, ranks, playerRanks, challenges, challengeRows] =
await Promise.all([
db
.select()
.from(trackerGames)
.where(eq(trackerGames.franchise, 'call-of-duty'))
.orderBy(asc(trackerGames.releaseYear), asc(trackerGames.sortOrder)),
db
.select({
id: trackerItems.id,
gameId: trackerItems.gameId,
kind: trackerItems.kind,
name: trackerItems.name,
category: trackerItems.category,
postLaunch: trackerItems.postLaunch
})
.from(trackerItems),
userId
? db
.select({ itemId: trackerProgress.itemId, milestone: trackerProgress.milestone })
.from(trackerProgress)
.where(eq(trackerProgress.userId, userId))
: Promise.resolve([]),
userId
? db
.select({ itemId: trackerWeaponRanks.itemId, prestige: trackerWeaponRanks.prestige })
.from(trackerWeaponRanks)
.where(eq(trackerWeaponRanks.userId, userId))
: Promise.resolve([]),
userId
? db
.select({ gameId: trackerRanks.gameId })
.from(trackerRanks)
.where(eq(trackerRanks.userId, userId))
: Promise.resolve([]),
db
.select({
id: trackerChallenges.id,
gameId: trackerChallenges.gameId,
target: trackerChallenges.target
})
.from(trackerChallenges),
userId
? db
.select({
challengeId: trackerChallengeProgress.challengeId,
current: trackerChallengeProgress.current,
done: trackerChallengeProgress.done
})
.from(trackerChallengeProgress)
.where(eq(trackerChallengeProgress.userId, userId))
: []
]);
const done = new Set(progress.map((row) => `${row.itemId}:${row.milestone}`));
for (const rank of ranks) if (rank.prestige > 0) done.add(`${rank.itemId}:maxLevel`);
const byGame = Map.groupBy(items, (item) => item.gameId);
return gamesList.map((game) => {
const list = byGame.get(game.id) ?? [];
@@ -84,7 +92,28 @@ async function callOfDutySummary(userId: string | undefined) {
list.filter((item) => item.kind === 'achievement').map((item) => item.id),
(id, milestone) => done.has(`${id}:${milestone}`)
);
const weaponProgress = sumProgress(summary.milestones);
const challengesProgress = challengeProgress(
challenges.filter((c) => c.gameId === game.id),
challengeRows
);
const ranksProgress = {
value:
ranks.filter((rank) =>
list.some((item) => item.kind === 'weapon' && item.id === rank.itemId)
).length + Number(playerRanks.some((rank) => rank.gameId === game.id)),
total: list.filter((item) => item.kind === 'weapon').length + 1
};
return {
overall: combinedProgress([
weaponProgress,
ranksProgress,
summary.achievements,
challengesProgress
]),
weaponProgress,
challengesProgress,
slug: game.slug,
name: game.shortName,
releaseYear: game.releaseYear,
@@ -108,9 +137,23 @@ async function callOfDutySummary(userId: string | undefined) {
}
export const load: PageServerLoad = async ({ locals }) => {
const [pokemon, callOfDuty] = await Promise.all([
const [pokemon, callOfDuty, osu] = await Promise.all([
pokemonSummary(locals.user?.id),
callOfDutySummary(locals.user?.id)
callOfDutySummary(locals.user?.id),
locals.user
? db
.select({ kind: osuEntries.kind, achieved: osuEntries.achieved })
.from(osuEntries)
.where(eq(osuEntries.userId, locals.user.id))
: []
]);
return { pokemon, callOfDuty };
return {
pokemon,
callOfDuty,
codOverall: combinedProgress(callOfDuty.map((g) => g.overall)),
osuGoals: {
value: osu.filter((e) => e.kind === 'goal' && e.achieved).length,
total: osu.filter((e) => e.kind === 'goal').length
}
};
};

View File

@@ -1,107 +1,211 @@
<script lang="ts">
import { resolve } from '$app/paths';
import ProgressBar from '$lib/components/ProgressBar.svelte';
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
import GameLogo from '$lib/game-tracker/GameLogo.svelte';
import ProgressMeter from '$lib/game-tracker/ProgressMeter.svelte';
import type { PageProps } from './$types';
let { data }: PageProps = $props();
function percent(value: number, total: number) {
return total > 0 ? Math.round((value / total) * 100) : 0;
}
</script>
<div class="mx-auto max-w-6xl px-4 py-10 sm:px-6 sm:py-14">
<h1 class="text-4xl font-semibold tracking-tight sm:text-5xl">game tracker</h1>
<p class="mt-2 text-[var(--site-muted)]">
completionist progress: every Pokémon in every game, and every achievement, weapon and camo in
Call of Duty.
</p>
{#if !data.user}<p class="mt-6">
<div class="tracker-library mx-auto flex w-full max-w-[1600px] flex-col px-4 py-5 sm:px-6">
<div class="mb-5 flex flex-wrap items-end justify-between gap-2">
<div>
<p class="text-xs tracking-[.18em] text-muted-foreground uppercase">Your next session</p>
<h1 class="mt-1 text-3xl font-semibold tracking-tight">Game tracker</h1>
</div>
{#if !data.user}<a
class="text-sm text-muted-foreground underline"
href={resolve('/login?returnTo=/projects/game-tracker')}>Sign in to save progress</a
>{:else}<a
class="text-xs text-muted-foreground underline"
href={resolve('/projects/game-tracker/credits')}>Artwork credits</a
>{/if}
</div>
<div
class="mb-4 grid grid-cols-2 gap-3 rounded-xl border bg-card p-3 lg:grid-cols-4"
aria-label="Your completion dashboard"
>
<ProgressMeter
label="National collection"
progress={data.pokemon.caught}
detail={`${data.pokemon.caught.value} unique species caught`}
hint="Unique species caught across the Pokémon games in your rules, out of the full species catalog."
/>
<ProgressMeter
label="Species seen at least once"
progress={data.pokemon.seen}
color="sky"
detail={`${data.pokemon.seen.value} species discovered`}
/>
<ProgressMeter
label="Pokémon games completed"
progress={data.pokemon.completed}
color="amber"
hint="Games marked story complete, or with all default story milestones checked."
/>
<ProgressMeter
label="Call of Duty overall"
progress={data.codOverall}
color="violet"
detail="Mastery · achievements · challenges"
/>
</div>
<div class="series-grid grid min-h-0 flex-1 gap-4">
<section
class="series-column flex min-h-0 min-w-0 flex-col rounded-2xl border bg-card p-3"
aria-labelledby="pokemon-series"
>
<a
href={resolve('/login?returnTo=/projects/game-tracker')}
class="underline underline-offset-4">sign in</a
> to save your progress.
</p>{/if}
<section class="mt-10">
<h2 class="text-2xl font-semibold">Pokémon</h2>
<Card.Root class="mt-4 py-0 transition-colors hover:bg-muted/50"
><Card.Content class="p-0"
><a href={resolve('/projects/game-tracker/pokemon')} class="block p-5">
<div class="grid grid-cols-[minmax(0,1fr)_8rem_auto] items-center gap-3">
<p class="text-xl font-semibold">catchemall</p>
<div class="w-32">
<ProgressBar
value={data.pokemon.caught.entries}
max={data.pokemon.totals.entries}
label="Pokémon caught"
small
href={resolve('/projects/game-tracker/pokemon')}
class="series-heading mb-3 flex items-center gap-3 rounded-xl bg-amber-500/10 p-3 transition-colors hover:bg-amber-500/20"
>
<GameLogo slug="pokemon" name="Pokémon" class="h-12 w-24" />
<div class="min-w-0 flex-1">
<h2 id="pokemon-series" class="font-semibold">Pokémon</h2>
<p class="text-xs text-muted-foreground">Open your adventure journal →</p>
<p class="mt-1 text-xs text-muted-foreground">
{data.pokemon.caught.value} / {data.pokemon.caught.total} species
</p>
</div>
</a>
<div class="mb-3 space-y-2 rounded-lg bg-muted/20 p-2">
<ProgressMeter
label="Across every adventure"
progress={data.pokemon.overall}
color="amber"
compact
hint="Equal weight per game; collection and story stages each contribute."
/>
<ProgressMeter
label="Every game’s collection"
progress={data.pokemon.collection}
compact
hint="Each confirmed species/game pairing counts once, including trades and events."
/>
</div>
{#if data.pokemon.games.length}
<div class="collection-grid grid grid-cols-2 gap-2">
{#each data.pokemon.games as game (game.id)}
<a
class="game-row flex min-h-0 min-w-0 items-center gap-2 rounded-lg border px-2 py-1.5 transition-colors hover:border-amber-500/50 hover:bg-amber-500/5"
href={resolve(`/projects/game-tracker/pokemon?game=${game.slug ?? game.id}`)}
title={`${game.name} · ${game.releaseYear}`}
>
<GameLogo
slug={`pokemon/${game.slug}`}
name={game.name}
class="game-cover h-10 w-10"
/>
<div class="min-w-0 flex-1">
<p class="game-name text-xs leading-tight font-medium">{game.name}</p>
<p class="game-year mt-0.5 text-[10px] text-muted-foreground">
{game.releaseYear}{game.completed ? ' · ✓ story' : ''}
</p>
<ProgressMeter
label="Game progress"
progress={game.overall}
color="amber"
compact
/>
</div>
</a>
{/each}
</div>
{:else}<a
class="rounded-xl border border-dashed p-5 text-sm text-muted-foreground hover:text-foreground"
href={resolve('/projects/game-tracker/pokemon')}
>Choose your games in “set rules” to build your collection here.</a
>{/if}
</section>
<section
class="series-column flex min-h-0 min-w-0 flex-col rounded-2xl border bg-card p-3"
aria-labelledby="cod-series"
>
<div class="series-heading mb-3 flex items-center gap-3 rounded-xl bg-zinc-500/10 p-3">
<GameLogo slug="call-of-duty" name="Call of Duty" class="h-12 w-24" />
<div>
<h2 id="cod-series" class="font-semibold">Call of Duty</h2>
<p class="text-xs text-muted-foreground">
{data.callOfDuty.length} campaigns of progress
</p>
</div>
</div>
<div class="mb-3 px-1">
<ProgressMeter label="COD completion" progress={data.codOverall} color="violet" compact />
</div>
<div class="cod-rows grid min-h-0 gap-1.5">
{#each data.callOfDuty as game (game.slug)}
<a
href={resolve(`/projects/game-tracker/call-of-duty/${game.slug}`)}
class="game-row flex min-h-0 items-center gap-3 rounded-lg border p-2 transition-colors hover:border-primary/40 hover:bg-muted/50"
>
<GameLogo slug={`cod/${game.slug}`} name={game.name} class="h-11 w-24" />
<div class="min-w-0 flex-1">
<p class="text-sm leading-tight font-medium">{game.name}</p>
<p class="mt-1 text-[11px] text-muted-foreground">
{game.releaseYear}<span class="ml-2"
>{game.achievements.value}/{game.achievements.total} achievements</span
>
</p>
<ProgressMeter
label={`${game.name} progress`}
progress={game.overall}
color="violet"
compact
/>
</div>
<p class="text-xl font-semibold tabular-nums">
{percent(data.pokemon.caught.entries, data.pokemon.totals.entries)}%
</p>
</a>
{/each}
</div>
</section>
<section
class="series-column flex min-w-0 flex-col rounded-2xl border bg-card p-3"
aria-labelledby="osu-series"
>
<div class="series-heading mb-3 flex items-center gap-3 rounded-xl bg-pink-500/10 p-3">
<GameLogo slug="osu" name="osu!" class="h-12 w-12" />
<div>
<h2 id="osu-series" class="font-semibold">osu!</h2>
<p class="text-xs text-muted-foreground">One more attempt</p>
</div>
</div>
<a
href={resolve('/projects/game-tracker/osu')}
class="rounded-xl border p-4 transition-colors hover:border-pink-500/50 hover:bg-pink-500/5"
><div class="flex items-center gap-3">
<GameLogo slug="osu" name="osu!" class="h-14 w-14" />
<div>
<p class="font-semibold">osu!</p>
<p class="text-xs text-muted-foreground">2007</p>
</div>
<p class="mt-2 text-[var(--site-muted)]">
{data.pokemon.caught.entries} of {data.pokemon.totals.entries} obtainable entries ·
{data.pokemon.caught.species} of {data.pokemon.totals.species} species · {data.pokemon
.totals.games} games
</p>
</a></Card.Content
></Card.Root
>
<Button variant="link" href={resolve('/projects/game-tracker/pokemon/locations')} class="mt-3"
>browse Pokémon locations</Button
>
</section>
<section class="mt-12">
<h2 class="text-2xl font-semibold">Call of Duty</h2>
<ul class="mt-4 grid gap-4 md:grid-cols-2">
{#each data.callOfDuty as game (game.slug)}
<li>
<Card.Root class="h-full py-0 transition-colors hover:bg-muted/50"
><Card.Content class="p-0"
><a
href={resolve('/projects/game-tracker/call-of-duty/[slug]', { slug: game.slug })}
class="block h-full p-5"
>
<div class="flex flex-wrap items-baseline justify-between gap-3">
<p class="text-xl font-semibold">{game.name}</p>
<p class="text-[var(--site-muted)]">{game.releaseYear}</p>
</div>
<dl class="mt-4 grid gap-3">
{#each [{ key: 'achievements', label: 'achievements', ...game.achievements }, ...game.milestones] as row (row.key)}
<div
class="grid grid-cols-[minmax(0,1fr)_8rem_auto] items-center gap-3 text-sm text-[var(--site-muted)]"
>
<dt class="truncate">{row.label}</dt>
<div class="w-32">
<ProgressBar value={row.value} max={row.total} label={row.label} small />
</div>
<dd class="min-w-12 text-right tabular-nums">{row.value}/{row.total}</dd>
</div>
{/each}
</dl>
{#if game.tiers.length}
<p class="mt-4 text-[var(--site-muted)]">
{game.tiers
.map((tier) =>
tier.scope === 'class'
? `${tier.label} ${tier.value}/${tier.total} classes`
: `${tier.label} ${tier.achieved ? '✓' : `${percent(tier.value, tier.total)}%`}`
)
.join(' · ')}
</p>
{/if}
</a></Card.Content
></Card.Root
>
</li>
{:else}
<li class="text-[var(--site-muted)]">the Call of Duty catalog has not been loaded yet.</li>
{/each}
</ul>
</section>
</div>
<p class="mt-4 text-sm">Your training room →</p>
<p class="mt-1 text-xs leading-relaxed text-muted-foreground">
Scores, dream FCs, stamina and speed. Build your next personal best.
</p>
<div class="mt-4">
<ProgressMeter label="osu! goals achieved" progress={data.osuGoals} color="pink" />
</div></a
>
</section>
</div>
</div>
<style>
.series-grid {
grid-template-columns: minmax(0, 1.5fr) minmax(0, 1.2fr) minmax(0, 0.8fr);
align-items: start;
}
.game-row {
min-height: 64px;
}
@media (max-width: 1100px) {
.series-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 639px) {
.series-grid {
grid-template-columns: minmax(0, 1fr);
}
}
</style>

View File

@@ -1,8 +1,20 @@
import { error, fail } from '@sveltejs/kit';
import { and, asc, eq } from 'drizzle-orm';
import achievementArt from '../../../../../../data/cod-achievement-art.json';
const achievementImages: Record<string, string> = achievementArt;
import { and, asc, eq, sql } from 'drizzle-orm';
import { db } from '$lib/server/db';
import { trackerGames, trackerItems, trackerProgress } from '$lib/server/db/schema';
import {
trackerGames,
trackerItems,
trackerProgress,
trackerRanks,
trackerWeaponRanks,
trackerChallenges,
trackerChallengeProgress
} from '$lib/server/db/schema';
import { boundedInteger } from '$lib/game-tracker/journal';
import { appliesTo } from '$lib/game-tracker/mastery';
import { playerRankLimits, weaponRankLimits } from '$lib/game-tracker/rank-limits';
import type { Actions, PageServerLoad } from './$types';
async function findGame(slug: string) {
@@ -36,9 +48,61 @@ export const load: PageServerLoad = async ({ params, locals }) => {
.innerJoin(trackerItems, eq(trackerItems.id, trackerProgress.itemId))
.where(and(eq(trackerProgress.userId, locals.user.id), eq(trackerItems.gameId, game.id)))
: [];
const [ranks, weaponRanks, challenges, challengeProgress] = await Promise.all([
locals.user
? db
.select()
.from(trackerRanks)
.where(and(eq(trackerRanks.userId, locals.user.id), eq(trackerRanks.gameId, game.id)))
: [],
locals.user
? db
.select({
itemId: trackerWeaponRanks.itemId,
level: trackerWeaponRanks.level,
prestige: trackerWeaponRanks.prestige
})
.from(trackerWeaponRanks)
.innerJoin(trackerItems, eq(trackerItems.id, trackerWeaponRanks.itemId))
.where(
and(eq(trackerWeaponRanks.userId, locals.user.id), eq(trackerItems.gameId, game.id))
)
: [],
db
.select()
.from(trackerChallenges)
.where(eq(trackerChallenges.gameId, game.id))
.orderBy(asc(trackerChallenges.category), asc(trackerChallenges.id)),
locals.user
? db
.select({
challengeId: trackerChallengeProgress.challengeId,
current: trackerChallengeProgress.current,
done: trackerChallengeProgress.done
})
.from(trackerChallengeProgress)
.innerJoin(
trackerChallenges,
eq(trackerChallenges.id, trackerChallengeProgress.challengeId)
)
.where(
and(
eq(trackerChallengeProgress.userId, locals.user.id),
eq(trackerChallenges.gameId, game.id)
)
)
: []
]);
return {
rank: ranks[0] ?? null,
weaponRanks,
challenges,
challengeProgress,
game: { slug: game.slug, name: game.name, shortName: game.shortName, rules: game.rules },
items,
items: items.map((item) => ({
...item,
icon: item.icon ? (achievementImages[item.icon] ?? item.icon) : null
})),
done: progress.map((row) => `${row.itemId}:${row.milestone}`),
seo: {
title: `${game.shortName} · Game Tracker`,
@@ -48,6 +112,151 @@ export const load: PageServerLoad = async ({ params, locals }) => {
};
export const actions = {
adjustWeaponRank: async ({ request, locals, params }) => {
if (!locals.user) return fail(401, { message: 'Sign in to save weapon progress.' });
const game = await findGame(params.slug);
const form = await request.formData();
const itemId = boundedInteger(form.get('itemId'), 1, 2147483647);
const field = form.get('field');
const delta = form.get('delta') === '1' ? 1 : form.get('delta') === '-1' ? -1 : null;
if (!itemId || !['level', 'prestige'].includes(String(field)) || delta === null)
return fail(400, { message: 'Invalid weapon adjustment.' });
const [item] = await db
.select({ id: trackerItems.id, name: trackerItems.name, category: trackerItems.category })
.from(trackerItems)
.where(
and(
eq(trackerItems.id, itemId),
eq(trackerItems.gameId, game.id),
eq(trackerItems.kind, 'weapon')
)
);
if (!item) return fail(404, { message: 'Weapon not found in this game.' });
const limits = weaponRankLimits(game.rules, item);
if (!limits.rankable)
return fail(400, {
message: 'This weapon does not have a weapon-rank progression in this game.'
});
const maxLevel = limits.maxLevel ?? 10000;
if (field === 'prestige' && delta > 0 && limits.canPrestigeOnlyAtMaxLevel) {
const [current] = await db
.select({ level: trackerWeaponRanks.level, prestige: trackerWeaponRanks.prestige })
.from(trackerWeaponRanks)
.where(
and(eq(trackerWeaponRanks.userId, locals.user.id), eq(trackerWeaponRanks.itemId, itemId))
);
if (!current || current.level < maxLevel || current.prestige >= limits.maxPrestige)
return fail(400, { message: `Reach weapon level ${maxLevel} before increasing prestige.` });
}
// Arithmetic happens in Postgres, so simultaneous taps from different devices cannot lose a level.
const [rank] = await db
.insert(trackerWeaponRanks)
.values({
userId: locals.user.id,
itemId,
level: field === 'level' ? Math.max(1, Math.min(maxLevel, 1 + delta)) : 1,
prestige: field === 'prestige' ? Math.max(0, delta) : 0
})
.onConflictDoUpdate({
target: [trackerWeaponRanks.userId, trackerWeaponRanks.itemId],
set: {
...(field === 'level'
? {
level: sql`greatest(1, least(${maxLevel}, ${trackerWeaponRanks.level} + ${delta}))`
}
: {
prestige: sql`greatest(0, least(${limits.maxPrestige}, ${trackerWeaponRanks.prestige} + ${delta}))`,
...(delta > 0 ? { level: 1 } : {})
}),
updatedAt: new Date()
}
})
.returning({
itemId: trackerWeaponRanks.itemId,
level: trackerWeaponRanks.level,
prestige: trackerWeaponRanks.prestige
});
return { rank };
},
saveRank: async ({ request, locals, params }) => {
if (!locals.user) return fail(401, { message: 'Sign in to save your rank.' });
const game = await findGame(params.slug);
const data = await request.formData();
const level = boundedInteger(data.get('level'), 1, 10000);
const prestige = boundedInteger(data.get('prestige'), 0, 1000);
const itemId = data.get('itemId') ? boundedInteger(data.get('itemId'), 1, 2147483647) : null;
if (level === null || prestige === null || (data.get('itemId') && !itemId))
return fail(400, { message: 'Enter a valid level and prestige.' });
if (itemId) {
const [item] = await db
.select()
.from(trackerItems)
.where(
and(
eq(trackerItems.id, itemId),
eq(trackerItems.gameId, game.id),
eq(trackerItems.kind, 'weapon')
)
);
if (!item) return fail(404, { message: 'Weapon not found in this game.' });
const limits = weaponRankLimits(game.rules, item);
if (
!limits.rankable ||
(limits.maxLevel !== null && level > limits.maxLevel) ||
prestige > limits.maxPrestige
)
return fail(400, { message: 'Enter a rank within this weapon’s level and prestige caps.' });
await db
.insert(trackerWeaponRanks)
.values({ userId: locals.user.id, itemId, level, prestige })
.onConflictDoUpdate({
target: [trackerWeaponRanks.userId, trackerWeaponRanks.itemId],
set: { level, prestige, updatedAt: new Date() }
});
} else {
const limits = playerRankLimits(game.rules);
if ((limits.maxLevel !== null && level > limits.maxLevel) || prestige > limits.maxPrestige)
return fail(400, { message: 'Enter a rank within this player level and prestige caps.' });
await db
.insert(trackerRanks)
.values({ userId: locals.user.id, gameId: game.id, level, prestige })
.onConflictDoUpdate({
target: [trackerRanks.userId, trackerRanks.gameId],
set: { level, prestige, updatedAt: new Date() }
});
}
return { saved: true };
},
saveChallenge: async ({ request, locals, params }) => {
if (!locals.user) return fail(401, { message: 'Sign in to track challenges.' });
const game = await findGame(params.slug);
const data = await request.formData();
const challengeId = boundedInteger(data.get('challengeId'), 1, 2147483647);
const current = boundedInteger(data.get('current'), 0, 2147483647);
if (!challengeId || current === null)
return fail(400, { message: 'Invalid challenge progress.' });
const [challenge] = await db
.select()
.from(trackerChallenges)
.where(and(eq(trackerChallenges.id, challengeId), eq(trackerChallenges.gameId, game.id)));
if (!challenge) return fail(404, { message: 'Challenge not found.' });
if (challenge.target !== null && current > challenge.target)
return fail(400, { message: 'Progress cannot exceed the target.' });
const values = {
userId: locals.user.id,
challengeId,
current,
done: data.get('done') === 'on' || (challenge.target !== null && current >= challenge.target)
};
await db
.insert(trackerChallengeProgress)
.values(values)
.onConflictDoUpdate({
target: [trackerChallengeProgress.userId, trackerChallengeProgress.challengeId],
set: values
});
return { saved: true };
},
toggle: async ({ request, locals, params }) => {
if (!locals.user) return fail(401, { message: 'Log in to track your progress' });
const game = await findGame(params.slug);

View File

@@ -1,14 +1,39 @@
<script lang="ts">
import WeaponRankControls from '$lib/game-tracker/WeaponRankControls.svelte';
import WeaponArtwork from '$lib/game-tracker/WeaponArtwork.svelte';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import { Button } from '$lib/components/ui/button/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Checkbox } from '$lib/components/ui/checkbox/index.js';
import { NativeSelect } from '$lib/components/ui/native-select/index.js';
import Crosshair from 'lucide-svelte/icons/crosshair';
import Trophy from 'lucide-svelte/icons/trophy';
import Target from 'lucide-svelte/icons/target';
import ChevronDown from 'lucide-svelte/icons/chevron-down';
import * as Collapsible from '$lib/components/ui/collapsible/index.js';
import GameLogo from '$lib/game-tracker/GameLogo.svelte';
import ProgressMeter from '$lib/game-tracker/ProgressMeter.svelte';
import { combinedProgress, sumProgress, challengeProgress } from '$lib/game-tracker/progress';
import { playerRankLimits, weaponRankLimits } from '$lib/game-tracker/rank-limits';
let rankOpen = $state(false);
let rankWeapon = $state<number | null>(null);
let challengeSearch = $state('');
let challengeCategory = $state('all');
let rankSaving = $state(false);
let challengePage = $state(1);
let weaponSearch = $state('');
let weaponClass = $state('all');
let overviewOpen = $state(false);
import { onMount } from 'svelte';
import { resolve } from '$app/paths';
import { deserialize } from '$app/forms';
import { SvelteSet } from 'svelte/reactivity';
import ProgressBar from '$lib/components/ProgressBar.svelte';
import { deserialize, enhance } from '$app/forms';
import { SvelteSet, SvelteMap } from 'svelte/reactivity';
import * as Tabs from '$lib/components/ui/tabs/index.js';
import { appliesTo, summarizeGame } from '$lib/game-tracker/mastery';
import type { PageProps } from './$types';
let { data }: PageProps = $props();
let { data, form }: PageProps = $props();
// rebuilt whenever the page data changes, so the server render already shows progress
const done = $derived(new SvelteSet(data.done));
const pending = new SvelteSet<string>();
@@ -16,7 +41,10 @@
// checkboxes stay disabled until hydration, so early clicks can't silently go unsaved
let hydrated = $state(false);
onMount(() => (hydrated = true));
const isDone = (id: number, milestone: string) => done.has(`${id}:${milestone}`);
const weaponRanks = $derived(new SvelteMap(data.weaponRanks.map((r) => [r.itemId, r])));
const isDone = (id: number, milestone: string) =>
done.has(`${id}:${milestone}`) ||
(milestone === 'maxLevel' && (weaponRanks.get(id)?.prestige ?? 0) > 0);
async function toggle(itemId: number, milestone: string, checked: boolean) {
const key = `${itemId}:${milestone}`;
@@ -55,6 +83,24 @@
isDone
)
);
const masteryProgress = $derived(sumProgress(summary.milestones));
const unlockProgress = $derived(challengeProgress(data.challenges, data.challengeProgress));
const rankProgress = $derived({
value: weaponRanks.size + Number(!!data.rank),
total: weapons.length + 1
});
const overall = $derived(
combinedProgress([masteryProgress, rankProgress, summary.achievements, unlockProgress])
);
const classesProgress = $derived(
rules.classes.map((category) => {
const members = weapons.filter((w) => w.category === category);
const tasks = members.flatMap((w) =>
rules.milestones.filter((m) => appliesTo(m, w)).map((m) => isDone(w.id, m.key))
);
return { category, value: tasks.filter(Boolean).length, total: tasks.length };
})
);
type Bar = {
label: string;
description?: string;
@@ -70,39 +116,74 @@
label: tier.scope === 'class' ? `${tier.label} classes` : tier.label
}))
]);
const classes = $derived(
rules.classes
.map((name) => {
const list = weapons.filter((weapon) => weapon.category === name);
const milestones = rules.milestones.filter((milestone) =>
list.some((weapon) => appliesTo(milestone, weapon))
);
const tiers = rules.tiers
.filter((tier) => tier.scope === 'class')
.map((tier) => ({ tier, count: summary.mastery.classTiers.get(tier.key)?.get(name) }))
.filter((entry) => entry.count);
return { name, list, milestones, tiers };
})
.filter((entry) => entry.list.length)
const weaponRows = $derived(
weapons.filter(
(w) =>
(weaponClass === 'all' || w.category === weaponClass) &&
w.name.toLowerCase().includes(weaponSearch.toLowerCase().trim()) &&
(!hideDone ||
rules.milestones.filter((m) => appliesTo(m, w)).some((m) => !isDone(w.id, m.key)))
)
);
const categories = $derived([...Map.groupBy(achievements, (item) => item.category)]);
const tabs = ['weapons', 'achievements'] as const;
const tabs = ['weapons', 'achievements', 'challenges'] as const;
let tab = $state<(typeof tabs)[number]>('weapons');
let hideDone = $state(false);
function percent(value: number, total: number) {
return total > 0 ? Math.round((value / total) * 100) : 0;
}
const rank = $derived(rankWeapon ? weaponRanks.get(rankWeapon) : data.rank);
const selectedWeapon = $derived(data.items.find((w) => w.id === rankWeapon));
const playerLimits = $derived(playerRankLimits(rules));
const rankLimits = $derived(
rankWeapon && selectedWeapon ? weaponRankLimits(rules, selectedWeapon) : playerLimits
);
const challengeCategories = $derived([...new Set(data.challenges.map((c) => c.category))]);
const challengeRows = $derived(
data.challenges.filter(
(c) =>
(challengeCategory === 'all' || c.category === challengeCategory) &&
`${c.name} ${c.requirement} ${c.reward ?? ''}`
.toLowerCase()
.includes(challengeSearch.toLowerCase()) &&
(!hideDone || !data.challengeProgress.find((p) => p.challengeId === c.id)?.done)
)
);
$effect(() => {
if (challengePage > Math.max(1, Math.ceil(challengeRows.length / 36))) challengePage = 1;
});
</script>
<div class="mx-auto max-w-6xl px-4 py-10 sm:px-6 sm:py-14">
<div class="mx-auto max-w-[1600px] px-3 py-4 sm:px-5">
<a
href={resolve('/projects/game-tracker')}
class="text-[var(--site-muted)] hover:text-[var(--site-text)]">← game tracker</a
>
<h1 class="mt-3 text-4xl font-semibold tracking-tight sm:text-5xl">{data.game.shortName}</h1>
<p class="mt-2 text-[var(--site-muted)]">
{weapons.length} weapons · {achievements.length} achievements
<div class="mt-3 flex flex-wrap items-center gap-3">
<GameLogo slug={`cod/${data.game.slug}`} name={data.game.shortName} class="h-12 w-24" />
<div class="flex-1">
<h1 class="text-2xl font-semibold tracking-tight">{data.game.shortName}</h1>
<p class="mt-2 text-muted-foreground">
Level {data.rank?.level ?? '—'}{playerLimits.maxLevel ? ` / ${playerLimits.maxLevel}` : ''} ·
Prestige {data.rank?.prestige ?? '—'}{data.game.rules.rankCaps
? ` / ${playerLimits.maxPrestige}`
: ''}{data.rank?.level === playerLimits.maxLevel &&
data.rank?.prestige === playerLimits.maxPrestige &&
data.game.rules.rankCaps
? ' · Prestige Master'
: ''}
</p>
</div>
<Button
variant="outline"
disabled={!hydrated || !data.user}
onclick={() => {
rankWeapon = null;
rankOpen = true;
}}>Update my rank</Button
>
</div>
<p class="mt-2 text-xs text-[var(--site-muted)]">
{weapons.length} weapons · {achievements.length} achievements · {data.challenges.length} challenges
& unlocks
</p>
{#if !data.user}<p class="mt-6">
<a
@@ -110,124 +191,170 @@
class="underline underline-offset-4">sign in</a
> to save your progress.
</p>{/if}
{#if form?.message}<p role="alert" class="mt-4 text-destructive">{form.message}</p>{/if}
{#if saveError}<p role="alert" class="mt-5 text-red-500">{saveError}</p>{/if}
<div
class="mt-8 grid gap-x-10 gap-y-7 border-y border-[var(--site-border)] py-6 sm:grid-cols-2 lg:grid-cols-3"
class="mt-3 grid grid-cols-2 gap-3 rounded-xl border bg-card p-3 sm:grid-cols-5"
aria-label="Game completion"
>
{#each bars as bar (bar.label)}
<div class="min-w-0" title={bar.description}>
<div class="flex flex-wrap items-baseline justify-between gap-2">
<p class="font-medium">{bar.label}</p>
<p class="text-xl font-semibold tabular-nums">
{bar.achieved ? '✓' : `${percent(bar.value, bar.total)}%`}
</p>
</div>
<div class="mt-3">
<ProgressBar value={bar.value} max={bar.total} label={bar.label} small />
</div>
<p class="mt-2 text-[var(--site-muted)]">{bar.value} of {bar.total}</p>
</div>
{/each}
<ProgressMeter
label="Game completion"
progress={overall}
color="violet"
compact
hint="Recorded ranks, weapon mastery, achievements and challenges contribute equally. Partial challenge targets count."
/>
<ProgressMeter label="Weapon mastery" progress={masteryProgress} color="amber" compact />
<ProgressMeter
label="Player & weapon ranks"
progress={rankProgress}
color="pink"
compact
hint="Percentage of this game’s player and weapon ranks that you have entered."
/>
<ProgressMeter label="Achievements" progress={summary.achievements} color="sky" compact />
<ProgressMeter label="Challenges & unlocks" progress={unlockProgress} compact />
</div>
<div class="mt-8 flex flex-wrap items-center justify-between gap-4">
<div
class="sticky top-0 z-20 mt-4 flex flex-wrap items-center justify-between gap-3 border-y bg-background/95 py-2"
>
<Tabs.Root bind:value={tab}
><Tabs.List
>{#each tabs as name (name)}<Tabs.Trigger value={name}>{name}</Tabs.Trigger
>{#each tabs as name (name)}<Tabs.Trigger disabled={!hydrated} value={name}>
{#if name === 'weapons'}<Crosshair class="mr-1.5 size-4" aria-hidden="true" />Weapons
{:else if name === 'achievements'}<Trophy
class="mr-1.5 size-4"
aria-hidden="true"
/>Achievements
{:else}<Target class="mr-1.5 size-4" aria-hidden="true" />Challenges{/if}</Tabs.Trigger
>{/each}</Tabs.List
></Tabs.Root
>
<label class="flex cursor-pointer items-center gap-3">
<input type="checkbox" bind:checked={hideDone} class="h-5 w-5 accent-[var(--site-text)]" />
hide finished
<Button variant="ghost" size="sm" onclick={() => (overviewOpen = true)}
>Progress overview</Button
>
<label class="flex cursor-pointer items-center gap-2 text-xs">
<Checkbox bind:checked={hideDone} />
Hide finished
</label>
</div>
{#if tab === 'weapons'}
{#if rules.tiers.length || rules.milestones.length}
<p class="mt-4 max-w-3xl text-[var(--site-muted)]">
{[...rules.milestones, ...rules.tiers]
.filter((rule) => rule.description)
.map((rule) => `${rule.label}: ${rule.description}`)
.join('. ')}. DLC weapons don’t count toward class or overall camos.
</p>
{/if}
{#each classes as group (group.name)}
{@const rows = group.list.filter(
(weapon) =>
!hideDone ||
group.milestones.some(
(milestone) => appliesTo(milestone, weapon) && !isDone(weapon.id, milestone.key)
)
)}
<section class="mt-10">
<div class="flex flex-wrap items-baseline justify-between gap-3">
<h2 class="text-2xl font-semibold">{group.name}</h2>
<p class="text-[var(--site-muted)]">
{#each group.tiers as { tier, count } (tier.key)}
<span class={count?.achieved ? 'ml-4 text-[var(--site-text)]' : 'ml-4'}
>{tier.label}
{count?.achieved ? '✓' : `${count?.value}/${count?.total}`}</span
<div class="my-3 flex flex-wrap items-center gap-2">
<Input
class="min-w-40 flex-1"
aria-label="Find a weapon"
type="search"
placeholder="Find a weapon…"
bind:value={weaponSearch}
/>
<NativeSelect aria-label="Weapon class" bind:value={weaponClass}
><option value="all">All weapon classes</option>{#each rules.classes as name (name)}<option
value={name}>{name}</option
>{/each}</NativeSelect
>
</div>
<div
class="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5"
aria-label="Weapon progress"
>
{#each weaponRows as weapon (weapon.id)}
{@const current = weaponRanks.get(weapon.id)}
{@const limits = weaponRankLimits(rules, weapon)}
{@const tiers = summary.mastery.weaponTiers(weapon)}
{@const allMilestones = rules.milestones.filter((m) => appliesTo(m, weapon))}
<article
class="weapon-card min-w-0 rounded-lg border bg-card p-2.5"
aria-label={weapon.name}
>
<div class="flex min-w-0 items-center gap-2">
<WeaponArtwork game={data.game.slug} name={weapon.name} icon={weapon.icon} />
<div class="min-w-0 flex-1">
<h2 class="truncate text-sm font-semibold" title={weapon.name}>{weapon.name}</h2>
<p class="truncate text-[10px] text-muted-foreground" title={weapon.category}>
{weapon.category}{weapon.postLaunch ? ' · DLC' : ''}
</p>
</div>
</div>
<div class="mt-2">
{#if limits.rankable}
<WeaponRankControls
itemId={weapon.id}
name={weapon.name}
level={current?.level ?? 1}
prestige={current?.prestige ?? 0}
levelCap={limits.maxLevel}
prestigeCap={limits.maxPrestige}
prestigeRequiresMaxLevel={limits.canPrestigeOnlyAtMaxLevel}
compact
disabled={!hydrated || !data.user}
onupdate={(r) => weaponRanks.set(r.itemId, r)}
onedit={() => {
rankWeapon = weapon.id;
rankOpen = true;
}}
/>
{:else}<p class="py-1 text-[10px] text-muted-foreground">No weapon level rank</p>{/if}
</div>
<div class="mt-2 flex items-center gap-2">
<ProgressMeter
label={`${weapon.name} mastery`}
progress={{
value: allMilestones.filter((m) => isDone(weapon.id, m.key)).length,
total: allMilestones.length
}}
color="amber"
compact
/>
{#if tiers.length}<span
class="shrink-0 text-[10px] text-amber-600"
title="Mastery tier"
>
{/each}
</p>
</div>
{#if rows.length}
<table class="mt-3 w-full border-collapse">
<thead>
<tr class="border-b border-[var(--site-border)] text-left text-[var(--site-muted)]">
<th scope="col" class="py-2 font-medium">weapon</th>
{#each group.milestones as milestone (milestone.key)}<th
scope="col"
class="w-20 py-2 text-center font-medium sm:w-28"
title={milestone.description}>{milestone.label}</th
{tiers.map((t) => t.label).join(' · ')}
</span>{/if}
</div>
{#if allMilestones.length}<Collapsible.Root class="mt-2 border-t pt-1.5">
<Collapsible.Trigger
class="group flex w-full items-center justify-between rounded py-1 text-left text-[11px] text-muted-foreground hover:text-foreground"
>
<span
>Camos & milestones <span class="ml-1 tabular-nums"
>{allMilestones.filter((m) => isDone(weapon.id, m.key))
.length}/{allMilestones.length}</span
></span
>
<ChevronDown
class="size-3.5 transition-transform group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</Collapsible.Trigger>
<Collapsible.Content class="mt-1 grid grid-cols-2 gap-x-2">
{#each allMilestones as milestone (milestone.key)}<label
class="flex min-h-7 items-center gap-1.5 text-[10px]"
><Checkbox
class="size-3.5"
checked={isDone(weapon.id, milestone.key)}
disabled={!hydrated ||
!data.user ||
pending.has(`${weapon.id}:${milestone.key}`)}
aria-label={`${weapon.name}: ${milestone.label}`}
title={milestone.description}
onCheckedChange={(checked) => toggle(weapon.id, milestone.key, checked)}
/>{milestone.label}</label
>{/each}
</tr>
</thead>
<tbody>
{#each rows as weapon (weapon.id)}
{@const tiers = summary.mastery.weaponTiers(weapon)}
<tr class="border-b border-[var(--site-border)]">
<th scope="row" class="py-2 text-left font-normal">
{weapon.name}
{#if weapon.postLaunch}<span class="ml-1 text-sm text-[var(--site-muted)]"
>DLC</span
>{/if}
{#if tiers.length}<span class="block text-sm text-[var(--site-muted)]"
>{tiers.map((tier) => tier.label).join(' · ')}</span
>{/if}
</th>
{#each group.milestones as milestone (milestone.key)}
<td class="py-2 text-center">
{#if appliesTo(milestone, weapon)}
<input
type="checkbox"
class="h-5 w-5 cursor-pointer accent-[var(--site-text)]"
checked={isDone(weapon.id, milestone.key)}
disabled={!hydrated ||
!data.user ||
pending.has(`${weapon.id}:${milestone.key}`)}
aria-label={`${weapon.name}: ${milestone.label}`}
title={data.user
? milestone.description
: 'Sign in to save your progress'}
onchange={(event) =>
toggle(weapon.id, milestone.key, event.currentTarget.checked)}
/>
{:else}<span class="text-[var(--site-muted)]">—</span>{/if}
</td>
{/each}
</tr>
{/each}
</tbody>
</table>
{:else}
<p class="mt-3 text-[var(--site-muted)]">all done.</p>
{/if}
</section>
{/each}
{:else}
</Collapsible.Content>
</Collapsible.Root>{/if}
</article>
{:else}<p class="col-span-full py-8 text-center text-muted-foreground">
No weapons match these filters.
</p>{/each}
</div>
<p class="mt-3 text-xs text-muted-foreground">
Showing {weaponRows.length} of {weapons.length} weapons · Changes save immediately. Prestige + starts
the next prestige at level 1.
</p>
{:else if tab === 'achievements'}
{#each categories as [category, list] (category)}
{@const rows = list.filter((item) => !hideDone || !isDone(item.id, 'done'))}
<section class="mt-10">
@@ -237,6 +364,17 @@
{list.filter((item) => isDone(item.id, 'done')).length} of {list.length}
</p>
</div>
<div class="mt-3">
<ProgressMeter
label={`${category} achievements`}
progress={{
value: list.filter((item) => isDone(item.id, 'done')).length,
total: list.length
}}
color="sky"
compact
/>
</div>
<ul class="mt-3">
{#each rows as item (item.id)}
<li class="border-t border-[var(--site-border)]">
@@ -256,13 +394,12 @@
>{item.description}</span
>{/if}
</span>
<input
type="checkbox"
<Checkbox
class="h-5 w-5 shrink-0 cursor-pointer accent-[var(--site-text)]"
checked={isDone(item.id, 'done')}
disabled={!hydrated || !data.user || pending.has(`${item.id}:done`)}
aria-label={`Unlocked ${item.name}`}
onchange={(event) => toggle(item.id, 'done', event.currentTarget.checked)}
onCheckedChange={(checked) => toggle(item.id, 'done', checked)}
/>
</label>
</li>
@@ -274,5 +411,230 @@
</ul>
</section>
{/each}
{:else}
<div class="mt-5 grid gap-3 sm:grid-cols-2">
<Input
type="search"
aria-label="Search challenges"
placeholder="Search challenges, emblems and calling cards…"
bind:value={challengeSearch}
oninput={() => (challengePage = 1)}
/><NativeSelect
class="w-full"
aria-label="Challenge category"
bind:value={challengeCategory}
onchange={() => (challengePage = 1)}
><option value="all">All categories</option
>{#each challengeCategories as category (category)}<option value={category}
>{category}</option
>{/each}</NativeSelect
>
</div>
<div class="mt-5 grid gap-4 md:grid-cols-2">
{#each challengeRows.slice((challengePage - 1) * 36, challengePage * 36) as challenge (challenge.id)}
{@const progress = data.challengeProgress.find((p) => p.challengeId === challenge.id)}
<article class="rounded-xl border bg-card p-5">
<div class="flex gap-3">
{#if challenge.icon}<img
src={challenge.icon}
alt=""
width="80"
height="48"
loading="lazy"
class="h-12 w-20 object-contain"
/>{/if}
<div>
<p class="text-xs text-muted-foreground">{challenge.category}</p>
<h2 class="font-semibold">{challenge.name}</h2>
</div>
</div>
<p class="mt-3 text-sm text-muted-foreground">{challenge.requirement}</p>
{#if challenge.reward}<p class="mt-2 text-sm">Unlock: {challenge.reward}</p>{/if}
<div class="mt-3">
<ProgressMeter
label={`${challenge.name} progress`}
progress={{
value: progress?.done ? (challenge.target ?? 1) : (progress?.current ?? 0),
total: challenge.target ?? 1
}}
detail={progress?.done
? 'Unlocked ✓'
: challenge.target
? `${progress?.current ?? 0} / ${challenge.target}`
: 'Not unlocked yet'}
/>
</div>
<form
method="POST"
action="?/saveChallenge"
use:enhance
class="mt-4 flex flex-wrap items-end gap-3"
>
<input
type="hidden"
name="challengeId"
value={challenge.id}
/>{#if challenge.target}<label class="flex-1 text-xs"
>Progress / {challenge.target}<Input
type="number"
name="current"
min={0}
max={challenge.target}
value={progress?.current ?? 0}
required
/></label
>{:else}<input type="hidden" name="current" value="0" />{/if}<label
class="mb-2 flex items-center gap-2 text-sm"
><Checkbox name="done" value="on" checked={progress?.done ?? false} />Unlocked</label
><Button type="submit" size="sm" variant="outline" disabled={!hydrated || !data.user}
>Save</Button
>
</form>
<!-- Catalog or validated external URL. -->
<!-- eslint-disable svelte/no-navigation-without-resolve -->
<a
href={challenge.sourceUrl}
target="_blank"
rel="noreferrer"
class="mt-3 inline-block text-xs text-muted-foreground underline"
>Source & requirements ↗</a
>
<!-- eslint-enable svelte/no-navigation-without-resolve -->
</article>
{:else}<p class="py-8 text-muted-foreground">
{data.challenges.length
? 'No matching challenges.'
: 'No multiplayer challenge catalog has been imported for this game yet.'}
</p>{/each}
</div>
<div class="mt-5 flex items-center justify-between">
<Button variant="outline" disabled={challengePage === 1} onclick={() => challengePage--}
>Previous</Button
><span class="text-sm text-muted-foreground"
>{challengeRows.length} challenges · {challengePage} / {Math.max(
1,
Math.ceil(challengeRows.length / 36)
)}</span
><Button
variant="outline"
disabled={challengePage * 36 >= challengeRows.length}
onclick={() => challengePage++}>Next</Button
>
</div>
<p class="mt-5 text-xs text-muted-foreground">
Requirements adapted from <a
href="https://callofduty.fandom.com/wiki/Challenges"
class="underline">Call of Duty Wiki contributors</a
>
under <a href="https://www.fandom.com/licensing" class="underline">CC BY-SA</a>. Each card
links to its source. This catalog includes confirmed source rows; coverage is not exhaustive.
</p>
{/if}
</div>
<Dialog.Root bind:open={rankOpen}
><Dialog.Content
><Dialog.Header
><Dialog.Title>{selectedWeapon?.name ?? 'Player'} level & prestige</Dialog.Title
><Dialog.Description
>Record your current rank in {data.game.shortName}. Weapon prestige also records that max
level has been reached.</Dialog.Description
></Dialog.Header
>{#if form?.message}<p role="alert" class="text-destructive">{form.message}</p>{/if}
<form
method="POST"
action="?/saveRank"
class="space-y-4"
use:enhance={() => {
rankSaving = true;
return async ({ result, update }) => {
await update();
rankSaving = false;
if (result.type === 'success') rankOpen = false;
};
}}
>
{#if rankWeapon}<input type="hidden" name="itemId" value={rankWeapon} />{/if}
<div class="grid grid-cols-2 gap-4">
<label
>Current level<Input
type="number"
name="level"
min={1}
max={rankLimits.maxLevel ?? 10000}
value={rank?.level ?? 1}
required
/></label
><label
>Prestige<Input
type="number"
name="prestige"
min={0}
max={rankLimits.maxPrestige}
value={rank?.prestige ?? 0}
required
/></label
>
</div>
<Dialog.Footer
><Button variant="outline" onclick={() => (rankOpen = false)}>Cancel</Button><Button
type="submit"
disabled={rankSaving || !data.user}>{rankSaving ? 'Saving…' : 'Save rank'}</Button
></Dialog.Footer
>
</form></Dialog.Content
></Dialog.Root
>
<Dialog.Root bind:open={overviewOpen}
><Dialog.Content class="max-h-[85dvh] overflow-y-auto sm:max-w-3xl"
><Dialog.Header
><Dialog.Title>Progress overview</Dialog.Title><Dialog.Description
>Mastery, camos and achievements in {data.game.shortName}.</Dialog.Description
></Dialog.Header
>
<div
class="grid gap-x-10 gap-y-7 border-y border-[var(--site-border)] py-6 sm:grid-cols-2 lg:grid-cols-3"
>
{#each bars as bar (bar.label)}
<ProgressMeter label={bar.label} progress={bar} color="amber" hint={bar.description} />
{/each}
</div>
<h3 class="font-semibold">Weapon classes</h3>
<div class="grid gap-4 sm:grid-cols-2">
{#each classesProgress as group (group.category)}<ProgressMeter
label={group.category}
progress={group}
color="amber"
/>{/each}
</div>
<div class="grid gap-4 sm:grid-cols-2">
<ProgressMeter
label="Ranks entered"
progress={rankProgress}
color="pink"
detail="Your player rank plus a saved rank for each weapon."
/>
<ProgressMeter
label="Challenges & unlocks"
progress={unlockProgress}
detail={`${data.challengeProgress.filter((p) => p.done).length} unlocked · partial targets count too`}
/><ProgressMeter
label="Weapons prestiged"
progress={{
value: weapons.filter((w) => (weaponRanks.get(w.id)?.prestige ?? 0) > 0).length,
total: weapons.length
}}
color="violet"
/>
</div>
<p class="text-xs text-muted-foreground">
{[...rules.milestones, ...rules.tiers]
.filter((r) => r.description)
.map((r) => `${r.label}: ${r.description}`)
.join('. ')}. DLC weapons do not gate class or overall camos.
</p>
</Dialog.Content></Dialog.Root
>

View File

@@ -0,0 +1,15 @@
import images from '../../../../../data/game-images.json';
import maps from '../../../../../data/pokemon-map-art.json';
export function load() {
const sources = new Map<string, { source: string; credit: string; count: number }>();
for (const image of images) {
const existing = sources.get(image.source);
if (existing) existing.count++;
else sources.set(image.source, { source: image.source, credit: image.credit, count: 1 });
}
return {
sources: [...sources.values()],
maps: Object.values(maps).map(({ name, source, credit }) => ({ name, source, credit })),
total: images.length
};
}

View File

@@ -0,0 +1,41 @@
<script lang="ts">
import { resolve } from '$app/paths';
import type { PageProps } from './$types';
let { data }: PageProps = $props();
</script>
<!-- Download manifest links point to reviewed external image sources. -->
<!-- eslint-disable svelte/no-navigation-without-resolve -->
<div class="mx-auto max-w-4xl px-4 py-10 sm:px-6">
<a href={resolve('/projects/game-tracker')} class="text-sm text-muted-foreground hover:underline"
>← Game tracker</a
>
<h1 class="mt-6 text-3xl font-semibold">Artwork credits</h1>
<p class="mt-3 text-muted-foreground">
Game covers, logos, sprites, maps and screenshots belong to their respective owners. The tracker
stores WebP copies for consistent, reliable display. Map imagery is shared across games in the
same region; later-region landmark positions are approximate.
</p>
<h2 class="mt-8 text-xl font-semibold">Regional maps</h2>
<ul class="mt-4 space-y-3">
{#each data.maps as map (map.name)}<li>
<a href={map.source} target="_blank" rel="noreferrer" class="font-medium underline"
>{map.name}</a
>
<p class="text-xs text-muted-foreground">{map.credit}</p>
</li>{/each}
</ul>
<h2 class="mt-8 text-xl font-semibold">Covers, sprites and other artwork</h2>
<p class="mt-2 text-sm text-muted-foreground">
{data.total.toLocaleString()} downloaded image records. Box art is archived by Libretro and Serebii;
Pokémon sprites and official artwork are archived by PokéAPI. COD covers and achievement icons come
from Steam.
</p>
<ul class="mt-4 space-y-3">
{#each data.sources as item (item.source)}<li>
<a href={item.source} target="_blank" rel="noreferrer" class="text-sm underline"
>{item.credit}</a
><span class="ml-2 text-xs text-muted-foreground">{item.count} images</span>
</li>{/each}
</ul>
</div>

View File

@@ -0,0 +1,133 @@
import { and, desc, eq } from 'drizzle-orm';
import { fail } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import { osuEntries } from '$lib/server/db/schema';
import { allowedOsuUrl, boundedInteger, validDate } from '$lib/game-tracker/journal';
import type { Actions, PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ locals }) => ({
entries: locals.user
? await db
.select()
.from(osuEntries)
.where(eq(osuEntries.userId, locals.user.id))
.orderBy(desc(osuEntries.playedOn), desc(osuEntries.id))
: [],
seo: {
title: 'osu! training · Game Tracker',
description:
'A personal journal for memorable scores, beatmap goals and speed, stamina, aim and reading practice.'
}
});
export const actions = {
save: async ({ request, locals }) => {
if (!locals.user) return fail(401, { message: 'Sign in to save training.' });
const data = await request.formData();
const t = (k: string) => String(data.get(k) ?? '').trim();
const id = t('id') ? boundedInteger(data.get('id'), 1, 2147483647) : null;
const kind = t('kind');
const mode = t('mode');
const goal = t('goal') || 'pass';
const skill = t('skill') || 'stamina';
if (
(t('id') && !id) ||
!['score', 'goal', 'training'].includes(kind) ||
!['osu', 'taiko', 'fruits', 'mania'].includes(mode) ||
!['pass', 'fc', 'accuracy', 'rank', 'custom'].includes(goal) ||
!['stamina', 'speed', 'aim', 'reading', 'rhythm', 'finger-control', 'consistency'].includes(
skill
) ||
!t('title') ||
t('title').length > 250 ||
t('notes').length > 5000 ||
t('mods').length > 80 ||
!validDate(t('playedOn'))
)
return fail(400, { message: 'Check the title, date and training details.' });
if (!allowedOsuUrl(t('beatmapUrl'), 'beatmap') || !allowedOsuUrl(t('scoreUrl'), 'score'))
return fail(400, { message: 'Use an https://osu.ppy.sh beatmap or score link.' });
const optionalInt = (key: string, min: number, max: number) =>
t(key) ? boundedInteger(data.get(key), min, max) : null;
const bpm = optionalInt('bpm', 1, 2000),
duration = optionalInt('duration', 1, 86400),
combo = optionalInt('combo', 0, 1000000),
misses = optionalInt('misses', 0, 1000000);
const decimal = (key: string, min: number, max: number) =>
!t(key) ||
(/^\d+(\.\d{1,4})?$/.test(t(key)) && Number(t(key)) >= min && Number(t(key)) <= max);
if (
(t('bpm') && bpm === null) ||
(t('duration') && duration === null) ||
(t('combo') && combo === null) ||
(t('misses') && misses === null) ||
!decimal('accuracy', 0, 100) ||
!decimal('pp', 0, 100000) ||
!t('rate') ||
!decimal('rate', 0.1, 4) ||
(kind === 'training' && (!bpm || !duration))
)
return fail(400, {
message:
'Training needs BPM and duration. Check numeric fields, accuracy (0–100) and rate (0.1–4).'
});
const values = {
userId: locals.user.id,
kind: kind as 'score' | 'goal' | 'training',
mode,
goal,
skill,
title: t('title'),
notes: t('notes'),
bpm,
duration,
combo,
misses,
accuracy: t('accuracy') || null,
pp: t('pp') || null,
rate: t('rate'),
mods: t('mods') || 'NM',
beatmapUrl: t('beatmapUrl') || null,
scoreUrl: t('scoreUrl') || null,
playedOn: t('playedOn'),
achieved: data.get('achieved') === 'on'
};
if (id) {
const updated = await db
.update(osuEntries)
.set(values)
.where(and(eq(osuEntries.id, id), eq(osuEntries.userId, locals.user.id)))
.returning({ id: osuEntries.id });
if (!updated.length) return fail(404, { message: 'Entry not found.' });
} else await db.insert(osuEntries).values(values);
return { saved: true };
},
toggleGoal: async ({ request, locals }) => {
if (!locals.user) return fail(401, { message: 'Sign in to update goals.' });
const data = await request.formData();
const id = boundedInteger(data.get('id'), 1, 2147483647);
if (!id) return fail(400, { message: 'Invalid goal.' });
const updated = await db
.update(osuEntries)
.set({ achieved: data.get('achieved') === 'on' })
.where(
and(
eq(osuEntries.id, id),
eq(osuEntries.userId, locals.user.id),
eq(osuEntries.kind, 'goal')
)
)
.returning({ id: osuEntries.id });
return updated.length ? { saved: true } : fail(404, { message: 'Goal not found.' });
},
delete: async ({ request, locals }) => {
if (!locals.user) return fail(401, { message: 'Sign in to remove entries.' });
const data = await request.formData();
const id = boundedInteger(data.get('id'), 1, 2147483647);
if (!id) return fail(400, { message: 'Invalid entry.' });
const removed = await db
.delete(osuEntries)
.where(and(eq(osuEntries.id, id), eq(osuEntries.userId, locals.user.id)))
.returning({ id: osuEntries.id });
return removed.length ? { saved: true } : fail(404, { message: 'Entry not found.' });
}
} satisfies Actions;

View File

@@ -0,0 +1,603 @@
<script lang="ts">
import { onMount } from 'svelte';
let hydrated = $state(false);
onMount(() => {
hydrated = true;
});
import { resolve } from '$app/paths';
import { enhance } from '$app/forms';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import * as AlertDialog from '$lib/components/ui/alert-dialog/index.js';
import * as Tabs from '$lib/components/ui/tabs/index.js';
import * as Table from '$lib/components/ui/table/index.js';
import { Button } from '$lib/components/ui/button/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Textarea } from '$lib/components/ui/textarea/index.js';
import { NativeSelect } from '$lib/components/ui/native-select/index.js';
import { Checkbox } from '$lib/components/ui/checkbox/index.js';
import { Badge } from '$lib/components/ui/badge/index.js';
import GameLogo from '$lib/game-tracker/GameLogo.svelte';
import ProgressMeter from '$lib/game-tracker/ProgressMeter.svelte';
import type { PageProps } from './$types';
let { data, form }: PageProps = $props();
type Entry = (typeof data.entries)[number];
let tab = $state('goals');
let open = $state(false);
let deleteOpen = $state(false);
let editing = $state<Entry | null>(null);
let kind = $state<'score' | 'goal' | 'training'>('goal');
let saving = $state(false);
let search = $state('');
let modeFilter = $state('all');
let skillFilter = $state('stamina');
let minDuration = $state(30);
const skills = ['stamina', 'speed', 'aim', 'reading', 'rhythm', 'finger-control', 'consistency'];
const modeName: Record<string, string> = {
osu: 'osu!',
taiko: 'osu!taiko',
fruits: 'osu!catch',
mania: 'osu!mania'
};
const scoped = $derived(
data.entries.filter(
(e) =>
(modeFilter === 'all' || e.mode === modeFilter) &&
`${e.title} ${e.notes} ${e.mods}`.toLowerCase().includes(search.toLowerCase())
)
);
const scores = $derived(scoped.filter((e) => e.kind === 'score'));
const goals = $derived(scoped.filter((e) => e.kind === 'goal'));
const sessions = $derived(scoped.filter((e) => e.kind === 'training'));
const allGoals = $derived(data.entries.filter((e) => e.kind === 'goal'));
const eligible = $derived(
sessions.filter((s) => s.skill === skillFilter && (s.duration ?? 0) >= minDuration)
);
const best = $derived(eligible.reduce((n, e) => Math.max(n, (e.bpm ?? 0) * Number(e.rate)), 0));
const chart = $derived(
[...eligible].sort((a, b) => a.playedOn.localeCompare(b.playedOn) || a.id - b.id).slice(-30)
);
const maxBpm = $derived(Math.max(1, ...chart.map((e) => (e.bpm ?? 0) * Number(e.rate))));
const minBpm = $derived(
Math.max(0, Math.min(...chart.map((e) => (e.bpm ?? 0) * Number(e.rate))) - 20)
);
function create(next: typeof kind, entry: Entry | null = null) {
kind = next;
editing = entry;
open = true;
}
function bpm(entry: Entry) {
return Math.round((entry.bpm ?? 0) * Number(entry.rate) * 10) / 10;
}
</script>
<div class="mx-auto max-w-6xl px-3 py-4 sm:px-5">
<a
href={resolve('/projects/game-tracker')}
class="text-sm text-muted-foreground hover:text-foreground">← game tracker</a
>
<div class="mt-3 flex flex-wrap items-center gap-3">
<GameLogo slug="osu" name="osu!" class="h-12 w-12 rounded-full bg-pink-500/10 text-pink-500" />
<div class="flex-1">
<p class="text-xs font-semibold tracking-[.2em] text-pink-500 uppercase">One more try</p>
<h1 class="mt-1 text-2xl font-semibold tracking-tight">osu! training</h1>
<p class="mt-1 text-xs text-muted-foreground">
Chase the FC. Build your stamina. Remember the scores that mattered.
</p>
</div>
<Button
disabled={!hydrated || !data.user}
onclick={() => create(tab === 'scores' ? 'score' : tab === 'training' ? 'training' : 'goal')}
>+ {tab === 'scores'
? 'Record a score'
: tab === 'training'
? 'Log practice'
: 'Set a goal'}</Button
>
</div>
{#if !data.user}<p class="mt-6">
<a class="underline" href={resolve('/login?returnTo=/projects/game-tracker/osu')}>Sign in</a> to
start your training journal.
</p>{/if}
{#if form?.message && !open && !deleteOpen}<p class="mt-4 text-destructive" role="alert">
{form.message}
</p>{/if}
<div class="my-3 grid grid-cols-3 gap-2">
<div class="rounded-xl border px-3 py-2">
<p class="text-xl font-semibold tabular-nums">
{data.entries.filter((e) => e.kind === 'score').length}
</p>
<p class="mt-1 text-xs text-muted-foreground">memorable scores</p>
</div>
<div class="rounded-xl border px-3 py-2">
<p class="text-xl font-semibold tabular-nums">
{data.entries.filter((e) => e.kind === 'goal' && e.achieved).length}<span
class="text-base text-muted-foreground"
>
/ {data.entries.filter((e) => e.kind === 'goal').length}</span
>
</p>
<p class="mt-1 text-xs text-muted-foreground">goals achieved</p>
</div>
<div class="rounded-xl border px-3 py-2">
<p class="text-xl font-semibold tabular-nums">
{Math.round(
data.entries
.filter((e) => e.kind === 'training')
.reduce((n, e) => n + (e.duration ?? 0), 0) / 60
)}
</p>
<p class="mt-1 text-xs text-muted-foreground">minutes of logged practice</p>
</div>
</div>
<div class="mb-3 grid grid-cols-2 gap-3 rounded-xl border bg-card p-3 sm:grid-cols-4">
<ProgressMeter
label="All map goals"
progress={{ value: allGoals.filter((g) => g.achieved).length, total: allGoals.length }}
color="pink"
compact
/>
{#each [{ kind: 'pass', label: 'Pass goals' }, { kind: 'fc', label: 'Full combo goals' }, { kind: 'accuracy', label: 'Accuracy goals' }] as group (group.kind)}
<ProgressMeter
label={group.label}
progress={{
value: allGoals.filter((g) => g.goal === group.kind && g.achieved).length,
total: allGoals.filter((g) => g.goal === group.kind).length
}}
color="pink"
compact
/>
{/each}
</div>
<div class="mb-5 flex gap-3">
<Input
type="search"
bind:value={search}
aria-label="Search osu journal"
placeholder="Search maps, scores or notes…"
/><NativeSelect aria-label="Game mode" bind:value={modeFilter}
><option value="all">All modes</option
>{#each Object.entries(modeName) as [value, label] (value)}<option {value}>{label}</option
>{/each}</NativeSelect
>
</div>
<Tabs.Root bind:value={tab}
><Tabs.List
><Tabs.Trigger disabled={!hydrated} value="goals">Map goals</Tabs.Trigger><Tabs.Trigger
disabled={!hydrated}
value="scores">Score showcase</Tabs.Trigger
><Tabs.Trigger disabled={!hydrated} value="training">Training log</Tabs.Trigger></Tabs.List
>
<Tabs.Content value="goals" class="mt-5"
><div class="grid gap-4 sm:grid-cols-2">
{#each goals as goal (goal.id)}<article class="rounded-xl border bg-card p-5">
<div class="flex items-center justify-between">
<Badge variant={goal.achieved ? 'secondary' : 'outline'}
>{goal.achieved ? '✓ achieved' : goal.goal.toUpperCase()}</Badge
><span class="text-xs text-muted-foreground">{modeName[goal.mode]} · {goal.mods}</span
>
</div>
<h2 class="mt-3 text-lg font-semibold">{goal.title}</h2>
{#if goal.notes}<p class="mt-2 whitespace-pre-wrap text-sm text-muted-foreground">
{goal.notes}
</p>{/if}
<div class="mt-4 flex items-center gap-3">
{#if goal.beatmapUrl}<!-- Catalog or validated external URL. -->
<!-- eslint-disable svelte/no-navigation-without-resolve -->
<a href={goal.beatmapUrl} target="_blank" rel="noreferrer" class="text-sm underline"
>Open beatmap ↗</a
>
<!-- eslint-enable svelte/no-navigation-without-resolve -->{/if}<Button
size="sm"
variant="ghost"
onclick={() => create('goal', goal)}>Edit</Button
>
<form method="POST" action="?/toggleGoal" use:enhance class="ml-auto">
<input type="hidden" name="id" value={goal.id} /><input
type="hidden"
name="achieved"
value={goal.achieved ? '' : 'on'}
/><Button type="submit" variant={goal.achieved ? 'outline' : 'default'} size="sm"
>{goal.achieved ? 'Reopen' : 'Achieved!'}</Button
>
</form>
</div>
</article>{:else}<div
class="col-span-full rounded-xl border border-dashed p-12 text-center"
>
<p class="text-xl font-semibold">What’s your next breakthrough?</p>
<p class="mt-2 text-sm text-muted-foreground">
A first pass, a clean FC, 99% accuracy, or a challenge of your own.
</p>
<Button
class="mt-5"
variant="outline"
disabled={!hydrated || !data.user}
onclick={() => create('goal')}>Set a goal</Button
>
</div>{/each}
</div></Tabs.Content
>
<Tabs.Content value="scores" class="mt-5"
><div class="grid gap-4 sm:grid-cols-2">
{#each scores as score (score.id)}<article class="rounded-xl border bg-card p-5">
<div class="flex items-center justify-between">
<Badge variant="secondary">{score.mods}</Badge><span
class="text-xs text-muted-foreground"
>{score.playedOn} · {modeName[score.mode]}</span
>
</div>
<h2 class="mt-3 text-lg font-semibold">{score.title}</h2>
<div class="mt-4 flex flex-wrap gap-5">
{#if score.accuracy}<p class="text-2xl font-semibold">
{score.accuracy}<span class="text-sm text-muted-foreground">%</span>
</p>{/if}{#if score.pp}<p class="text-2xl font-semibold text-pink-500">
{score.pp}<span class="text-sm"> pp</span>
</p>{/if}{#if score.combo !== null}<p class="text-2xl font-semibold">
{score.combo}<span class="text-sm text-muted-foreground">x</span>
</p>{/if}
</div>
<p class="mt-2 text-sm text-muted-foreground">
{score.misses !== null ? `${score.misses} misses · ` : ''}{score.rate}× rate
</p>
{#if score.notes}<p class="mt-3 whitespace-pre-wrap text-sm text-muted-foreground">
{score.notes}
</p>{/if}
<div class="mt-4 flex gap-4">
{#if score.scoreUrl}<!-- Catalog or validated external URL. -->
<!-- eslint-disable svelte/no-navigation-without-resolve -->
<a href={score.scoreUrl} target="_blank" rel="noreferrer" class="text-sm underline"
>View score ↗</a
>
<!-- eslint-enable svelte/no-navigation-without-resolve -->{/if}{#if score.beatmapUrl}<!-- Catalog or validated external URL. -->
<!-- eslint-disable svelte/no-navigation-without-resolve -->
<a
href={score.beatmapUrl}
target="_blank"
rel="noreferrer"
class="text-sm underline">Beatmap ↗</a
>
<!-- eslint-enable svelte/no-navigation-without-resolve -->{/if}<Button
class="ml-auto"
size="sm"
variant="ghost"
onclick={() => create('score', score)}>Edit</Button
>
</div>
</article>{:else}<div
class="col-span-full rounded-xl border border-dashed p-12 text-center"
>
<p class="text-xl font-semibold">Some scores deserve a place on the wall.</p>
<p class="mt-2 text-sm text-muted-foreground">
Keep the play, your accuracy, mods, pp, and why it mattered.
</p>
<Button
class="mt-5"
variant="outline"
disabled={!hydrated || !data.user}
onclick={() => create('score')}>Record a score</Button
>
</div>{/each}
</div></Tabs.Content
>
<Tabs.Content value="training" class="mt-5">
<section class="rounded-xl border p-5">
<div class="flex flex-wrap items-end justify-between gap-4">
<div>
<p class="text-xs font-semibold tracking-widest text-muted-foreground uppercase">
Sustained pace
</p>
<p class="mt-2 text-3xl font-semibold">
{best || '—'} <span class="text-base text-muted-foreground">effective BPM</span>
</p>
</div>
<div class="flex gap-3">
<label class="text-xs"
>Skill<NativeSelect bind:value={skillFilter} class="mt-1"
>{#each skills as skill (skill)}<option value={skill}>{skill}</option
>{/each}</NativeSelect
></label
><label class="text-xs"
>Minimum seconds<Input
type="number"
min={1}
max={86400}
bind:value={minDuration}
class="mt-1 w-28"
/></label
>
</div>
</div>
<p class="mt-3 text-xs text-muted-foreground">
Best recorded pace for the selected mode and skill, sustained for at least {minDuration} seconds.
Effective BPM = map BPM × playback rate.
</p>
{#if chart.length > 1}<svg
viewBox="0 0 640 150"
role="img"
aria-label={`Last ${chart.length} qualifying ${skillFilter} sessions, ${minBpm} to ${maxBpm} effective BPM`}
class="mt-5 h-40 w-full overflow-visible"
><line x1="10" x2="630" y1="135" y2="135" stroke="currentColor" opacity=".2" /><polyline
points={chart
.map(
(e, i) =>
`${10 + (i / (chart.length - 1)) * 620},${130 - ((bpm(e) - minBpm) / (maxBpm - minBpm || 1)) * 110}`
)
.join(' ')}
fill="none"
stroke="#ec4899"
stroke-width="2"
/>{#each chart as e, i (e.id)}<circle
cx={10 + (i / (chart.length - 1)) * 620}
cy={130 - ((bpm(e) - minBpm) / (maxBpm - minBpm || 1)) * 110}
r="4"
fill="#ec4899"
><title>{e.playedOn} · {bpm(e)} BPM · {e.duration}s · {e.title}</title></circle
>{/each}</svg
>{:else}<p class="mt-5 rounded-lg bg-muted/40 p-4 text-sm text-muted-foreground">
Log two qualifying sessions to see your pace over time.
</p>{/if}
</section>
<div class="mt-5 overflow-x-auto">
<Table.Root
><Table.Header
><Table.Row
><Table.Head>Session</Table.Head><Table.Head>Skill</Table.Head><Table.Head
>BPM</Table.Head
><Table.Head>Duration</Table.Head><Table.Head>Accuracy</Table.Head><Table.Head
></Table.Head></Table.Row
></Table.Header
><Table.Body
>{#each sessions as session (session.id)}<Table.Row
><Table.Cell
><span class="font-medium">{session.title}</span><span
class="block text-xs text-muted-foreground"
>{session.playedOn} · {modeName[session.mode]}</span
></Table.Cell
><Table.Cell>{session.skill}</Table.Cell><Table.Cell
>{bpm(session)}<span class="block text-xs text-muted-foreground"
>{session.bpm} × {session.rate}</span
></Table.Cell
><Table.Cell>{session.duration}s</Table.Cell><Table.Cell
>{session.accuracy ? `${session.accuracy}%` : '—'}</Table.Cell
><Table.Cell
><Button size="sm" variant="ghost" onclick={() => create('training', session)}
>Edit</Button
></Table.Cell
></Table.Row
>{:else}<Table.Row
><Table.Cell colspan={6} class="py-10 text-center text-muted-foreground"
>Log a practice session to start building your training history.</Table.Cell
></Table.Row
>{/each}</Table.Body
></Table.Root
>
</div>
</Tabs.Content>
</Tabs.Root>
</div>
<Dialog.Root bind:open
><Dialog.Content class="max-h-[90dvh] overflow-y-auto sm:max-w-2xl"
><Dialog.Header
><Dialog.Title
>{editing ? 'Edit' : kind === 'score' ? 'Record' : kind === 'goal' ? 'Set' : 'Log'}
{kind === 'training' ? 'practice session' : kind}</Dialog.Title
><Dialog.Description
>{kind === 'goal'
? 'Give yourself something worth chasing.'
: kind === 'score'
? 'Save the numbers and the story behind this play.'
: 'Track the pace you can sustain and what you want to work on next.'}</Dialog.Description
></Dialog.Header
>{#if form?.message}<p role="alert" class="text-destructive">{form.message}</p>{/if}
{#key `${kind}-${editing?.id ?? 'new'}`}
<form
method="POST"
action="?/save"
class="space-y-4"
use:enhance={() => {
saving = true;
return async ({ result, update }) => {
await update({ reset: false });
saving = false;
if (result.type === 'success') open = false;
};
}}
>
<input type="hidden" name="kind" value={kind} />{#if editing}<input
type="hidden"
name="id"
value={editing.id}
/>{/if}
<label class="block"
>{kind === 'training' ? 'Session name' : 'Map / achievement'}<Input
name="title"
required
maxlength={250}
value={editing?.title ?? ''}
placeholder={kind === 'training'
? '180 BPM stream practice'
: 'Artist — Title [Difficulty]'}
/></label
>
<div class="grid grid-cols-2 gap-4">
<label
>Mode<NativeSelect name="mode" value={editing?.mode ?? 'osu'} class="w-full"
>{#each Object.entries(modeName) as [value, label] (value)}<option {value}
>{label}</option
>{/each}</NativeSelect
></label
><label
>Date<Input
type="date"
name="playedOn"
required
value={editing?.playedOn ?? new Date().toISOString().slice(0, 10)}
/></label
>
</div>
<label class="block"
>Beatmap link (optional)<Input
type="url"
name="beatmapUrl"
placeholder="https://osu.ppy.sh/beatmaps/…"
value={editing?.beatmapUrl ?? ''}
/></label
>
{#if kind === 'score'}<label class="block"
>Score link (optional)<Input
type="url"
name="scoreUrl"
placeholder="https://osu.ppy.sh/scores/…"
value={editing?.scoreUrl ?? ''}
/></label
>{/if}
{#if kind === 'goal'}<div class="flex items-end gap-4">
<label class="flex-1"
>Goal<NativeSelect class="w-full" name="goal" value={editing?.goal ?? 'pass'}
><option value="pass">Pass</option><option value="fc">Full combo</option><option
value="accuracy">Accuracy target</option
><option value="rank">Rank / pp target</option><option value="custom"
>Personal challenge</option
></NativeSelect
></label
><label class="mb-2 flex items-center gap-2"
><Checkbox
name="achieved"
value="on"
checked={editing?.achieved ?? false}
/>Achieved</label
>
</div>{/if}
{#if kind === 'training'}<label class="block"
>Skill<NativeSelect name="skill" value={editing?.skill ?? 'stamina'} class="w-full"
>{#each skills as skill (skill)}<option value={skill}>{skill}</option
>{/each}</NativeSelect
></label
>{/if}
<div class="grid grid-cols-2 gap-4">
<label
>Mods<Input
name="mods"
value={editing?.mods ?? 'NM'}
maxlength={80}
placeholder="NM, HD, DT…"
/></label
><label
>Playback rate<Input
type="number"
name="rate"
min={0.1}
max={4}
step="0.01"
required
value={Number(editing?.rate ?? 1)}
/></label
><label
>Map BPM{kind !== 'training' ? ' (optional)' : ''}<Input
type="number"
name="bpm"
min={1}
max={2000}
required={kind === 'training'}
value={editing?.bpm ?? undefined}
/></label
><label
>Duration (seconds)<Input
type="number"
name="duration"
min={1}
max={86400}
required={kind === 'training'}
value={editing?.duration ?? undefined}
/></label
><label
>Accuracy %<Input
type="number"
name="accuracy"
min={0}
max={100}
step="0.01"
value={editing?.accuracy ? Number(editing.accuracy) : undefined}
/></label
>{#if kind !== 'training'}<label
>pp<Input
type="number"
name="pp"
min={0}
max={100000}
step="0.01"
value={editing?.pp ? Number(editing.pp) : undefined}
/></label
><label
>Max combo<Input
type="number"
name="combo"
min={0}
max={1000000}
value={editing?.combo ?? undefined}
/></label
><label
>Misses<Input
type="number"
name="misses"
min={0}
max={1000000}
value={editing?.misses ?? undefined}
/></label
>{/if}
</div>
<p class="text-xs text-muted-foreground">
Enter the actual playback rate, including DT, HT or custom rate changes. BPM is the map’s
original tempo.
</p>
<label class="block"
>Notes / target<Textarea
name="notes"
maxlength={5000}
value={editing?.notes ?? ''}
placeholder="What felt good? What needs work? What is the next target?"
/></label
>
<Dialog.Footer
><Button variant="outline" onclick={() => (open = false)}>Cancel</Button><Button
type="submit"
disabled={!data.user || saving}>{saving ? 'Saving…' : 'Save entry'}</Button
></Dialog.Footer
>
</form>{/key}
{#if editing}<Button
variant="ghost"
class="justify-self-start text-destructive"
onclick={() => (deleteOpen = true)}>Delete entry</Button
>{/if}
</Dialog.Content></Dialog.Root
>
<AlertDialog.Root bind:open={deleteOpen}
><AlertDialog.Content
><AlertDialog.Header
><AlertDialog.Title>Delete this entry?</AlertDialog.Title><AlertDialog.Description
>This removes “{editing?.title}” from your journal.</AlertDialog.Description
></AlertDialog.Header
>{#if form?.message}<p role="alert" class="text-destructive">{form.message}</p>{/if}
<form
method="POST"
action="?/delete"
use:enhance={() =>
async ({ result, update }) => {
await update();
if (result.type === 'success') {
deleteOpen = false;
open = false;
}
}}
>
<input type="hidden" name="id" value={editing?.id ?? ''} /><AlertDialog.Footer
><AlertDialog.Cancel>Keep entry</AlertDialog.Cancel><Button
type="submit"
variant="destructive">Delete entry</Button
></AlertDialog.Footer
>
</form></AlertDialog.Content
></AlertDialog.Root
>

View File

@@ -1,3 +1,16 @@
import { pokemonJournalActions, catchesFor } from '$lib/server/pokemon-journal';
import { loadPokemonProgress } from '$lib/server/tracker-progress';
import {
pokemonCatches,
pokemonDexNumbers,
pokemonJourneys,
pokemonMilestones,
pokemonGameResearch,
pokemonLocations,
pokemonEncounters,
pokemonSeen
} from '$lib/server/db/schema';
import { sql } from 'drizzle-orm';
import { db } from '$lib/server/db';
import {
games,
@@ -14,13 +27,15 @@ import { requireAdmin } from '$lib/server/authorization';
import { fail } from '@sveltejs/kit';
export type WireEntry = [id: number, gameId: number, availability: number, note?: string];
export const load: PageServerLoad = async ({ locals }) => {
export const load: PageServerLoad = async ({ locals, url }) => {
const [pokemonRows, entryRows, gameRows] = await Promise.all([
db
.select({
id: pokemonTable.id,
number: pokemonTable.number,
name: pokemonTable.name
name: pokemonTable.name,
type1: pokemonTable.type1,
type2: pokemonTable.type2
})
.from(pokemonTable)
.orderBy(asc(pokemonTable.number)),
@@ -34,7 +49,7 @@ export const load: PageServerLoad = async ({ locals }) => {
})
.from(pokemonGameEntries),
db
.select({ id: games.id, name: games.name, generation: games.generation })
.select({ id: games.id, name: games.name, slug: games.slug, generation: games.generation })
.from(games)
.orderBy(asc(games.generation), asc(games.id))
]);
@@ -69,8 +84,83 @@ export const load: PageServerLoad = async ({ locals }) => {
selectedGameIds = gameRows.map((r) => r.id);
}
const visible =
gamesConfigured || selectedGameIds.length
? gameRows.filter((g) => selectedGameIds.includes(g.id))
: gameRows;
const requested = url.searchParams.get('game');
const activeGame =
visible.find((g) => g.slug === requested || String(g.id) === requested) ??
visible.find((g) => g.slug === 'platinum') ??
visible[0] ??
null;
const gameId = activeGame?.id ?? -1;
const [
dexNumbers,
catches,
journeyRows,
milestones,
researchRows,
locations,
progress,
seenRows
] = await Promise.all([
db.select().from(pokemonDexNumbers).where(eq(pokemonDexNumbers.gameId, gameId)),
catchesFor(locals.user?.id, gameId),
locals.user
? db
.select()
.from(pokemonJourneys)
.where(
and(eq(pokemonJourneys.userId, locals.user.id), eq(pokemonJourneys.gameId, gameId))
)
: [],
locals.user
? db
.select()
.from(pokemonMilestones)
.where(
and(eq(pokemonMilestones.userId, locals.user.id), eq(pokemonMilestones.gameId, gameId))
)
: [],
db.select().from(pokemonGameResearch).where(eq(pokemonGameResearch.gameId, gameId)),
db
.select({
id: pokemonLocations.id,
slug: pokemonLocations.slug,
name: pokemonLocations.name,
region: pokemonLocations.region,
count: sql<number>`count(distinct ${pokemonEncounters.pokemonId})`.mapWith(Number)
})
.from(pokemonLocations)
.leftJoin(
pokemonEncounters,
and(
eq(pokemonEncounters.locationId, pokemonLocations.id),
eq(pokemonEncounters.gameId, gameId)
)
)
.groupBy(pokemonLocations.id),
loadPokemonProgress(locals.user?.id),
locals.user
? db
.select({ pokemonId: pokemonSeen.pokemonId })
.from(pokemonSeen)
.where(and(eq(pokemonSeen.userId, locals.user.id), eq(pokemonSeen.gameId, gameId)))
: []
]);
return {
progress,
seenIds: seenRows.map((r) => r.pokemonId),
pokemon,
activeGame,
dexNumbers,
catches,
journey: journeyRows[0] ?? null,
milestones,
regions: researchRows[0]?.regions ?? [],
locations,
games: gameRows,
caughtIds,
selectedGameIds,
@@ -84,6 +174,7 @@ function entryId(data: FormData) {
}
export const actions = {
...pokemonJournalActions,
togglePokemonCaught: async ({ request, locals }) => {
if (!locals.user) return fail(401, { message: 'Log in to track your progress' });
@@ -91,32 +182,58 @@ export const actions = {
const id = entryId(data);
if (!id) return fail(400, { message: 'Invalid entry' });
// only obtainable entries can be toggled — the client disables the others
// but we can't trust that
// Verify the entry and allow historical checkmarks to be cleared even
// when source availability has since changed.
const [entry] = await db
.select({ availability: pokemonGameEntries.availability })
.select({
availability: pokemonGameEntries.availability,
gameId: pokemonGameEntries.gameId,
pokemonId: pokemonGameEntries.pokemonId
})
.from(pokemonGameEntries)
.where(eq(pokemonGameEntries.id, id));
if (!entry) return fail(404, { message: 'Unknown entry' });
if (!obtainableAvailability.has(entry.availability)) {
return fail(400, { message: 'This Pokémon has no confirmed way to obtain it in this game' });
}
if (data.has('caught') && data.get('caught') !== 'on')
return fail(400, { message: 'Invalid caught state' });
const caught = data.get('caught') === 'on';
if (caught && !obtainableAvailability.has(entry.availability))
return fail(400, { message: 'This Pokémon has no confirmed way to obtain it in this game' });
if (caught) {
await db
.insert(userEntries)
.values({ pokemonGameEntryId: id, userId: locals.user.id })
.onConflictDoNothing();
} else {
await db
.delete(userEntries)
.where(and(eq(userEntries.pokemonGameEntryId, id), eq(userEntries.userId, locals.user.id)));
}
return { saved: true };
const userId = locals.user.id;
return db.transaction(async (tx) => {
await tx.execute(sql`select pg_advisory_xact_lock(hashtext(${userId}), ${entry.gameId})`);
if (caught) {
await tx
.insert(userEntries)
.values({ pokemonGameEntryId: id, userId })
.onConflictDoNothing();
await tx
.insert(pokemonSeen)
.values({ userId, gameId: entry.gameId, pokemonId: entry.pokemonId })
.onConflictDoNothing();
} else {
const linked = await tx
.select({ id: pokemonCatches.id })
.from(pokemonCatches)
.where(
and(
eq(pokemonCatches.userId, userId),
eq(pokemonCatches.gameId, entry.gameId),
eq(pokemonCatches.pokemonId, entry.pokemonId)
)
)
.limit(1);
if (linked.length)
return fail(400, {
message: 'Remove the registered catches before clearing the caught checkmark.'
});
await tx
.delete(userEntries)
.where(and(eq(userEntries.pokemonGameEntryId, id), eq(userEntries.userId, userId)));
}
return { saved: true };
});
},
setGames: async ({ request, locals }) => {

View File

@@ -1,474 +1,192 @@
<script lang="ts">
import { onMount } from 'svelte';
import { resolve } from '$app/paths';
import { deserialize, enhance } from '$app/forms';
import { invalidateAll } from '$app/navigation';
import {
availabilityLabels,
availabilityValues,
obtainableAvailability,
type Availability
} from '$lib/availability';
import { SvelteSet } from 'svelte/reactivity';
import type { PageProps } from './$types';
import ProgressBar from '$lib/components/ProgressBar.svelte';
import { Button } from '$lib/components/ui/button/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import PokemonDetails from '$lib/catch-em-all/PokemonDetails.svelte';
import { summarizeProgress } from '$lib/catch-em-all/progress';
type Entry = { id: number; availability: Availability; note: string | null };
type Game = { id: number; name: string };
let { data, form }: PageProps = $props();
// rebuilt whenever the page data changes, so the server render already shows progress
const caught = $derived(new SvelteSet(data.caughtIds));
const pending = new SvelteSet<number>();
let saveError = $state('');
// checkboxes stay disabled until hydration, so early clicks can't silently go unsaved
let hydrated = $state(false);
onMount(() => (hydrated = true));
async function toggleCaught(entryId: number, checked: boolean) {
if (pending.has(entryId)) return;
pending.add(entryId);
saveError = '';
if (checked) caught.add(entryId);
else caught.delete(entryId);
const body = new FormData();
body.set('entryId', String(entryId));
if (checked) body.set('caught', 'on');
let failed: boolean;
try {
const response = await fetch('?/togglePokemonCaught', { method: 'POST', body });
const result = deserialize(await response.text());
failed = result.type !== 'success';
} catch {
failed = true;
}
pending.delete(entryId);
if (failed) {
saveError = 'Could not save your catch. Please try again, or log in again.';
if (checked) caught.delete(entryId);
else caught.add(entryId);
}
}
const entryMap = $derived(
new Map(
data.pokemon.map((pokemon) => [
pokemon.id,
new Map(
pokemon.entries.map(([id, gameId, code, note]) => [
gameId,
{ id, availability: availabilityValues[code], note: note ?? null } satisfies Entry
])
)
])
onMount(() => {
hydrated = true;
});
import { resolve } from '$app/paths';
import { goto } from '$app/navigation';
import { enhance } from '$app/forms';
import { SvelteSet } from 'svelte/reactivity';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import { Button } from '$lib/components/ui/button/index.js';
import { Checkbox } from '$lib/components/ui/checkbox/index.js';
import { chronologicalPokemon } from '$lib/game-tracker/game-art';
import GameLogo from '$lib/game-tracker/GameLogo.svelte';
import PokemonJournal from '$lib/game-tracker/PokemonJournal.svelte';
import type { PageProps } from './$types';
let { data, form }: PageProps = $props();
let rulesOpen = $state(false);
let stripWidth = $state(1000);
const coverRows = $derived(visibleGames.length > Math.floor((stripWidth + 4) / 68) ? 2 : 1);
let saving = $state(false);
const draft = new SvelteSet<number>();
const visibleGames = $derived(
chronologicalPokemon(
data.gamesConfigured
? data.games.filter((g) => data.selectedGameIds.includes(g.id))
: data.games
)
);
const selectedGameIds = $derived(new Set(data.selectedGameIds));
const visibleGames = $derived(
data.gamesConfigured ? data.games.filter((game) => selectedGameIds.has(game.id)) : data.games
);
let viewGameId = $state<number | null>(null);
$effect(() => {
if (!visibleGames.some((game) => game.id === viewGameId))
viewGameId = visibleGames[0]?.id ?? null;
});
const viewGame = $derived(visibleGames.find((game) => game.id === viewGameId));
const visibleGameIds = $derived(new Set(visibleGames.map((game) => game.id)));
const progress = $derived(summarizeProgress(data.pokemon, visibleGameIds, caught));
const progressBars = $derived([
{
label: 'seen at least once',
value: progress.seenPokemon,
total: progress.catchablePokemon,
unit: 'Pokémon'
},
{
label: 'caught in every game it’s in',
value: progress.completedPokemon,
total: progress.catchablePokemon,
unit: 'Pokémon'
},
{
label: 'games completed',
value: progress.completedGames,
total: progress.catchableGames,
unit: 'games'
}
]);
function percent(value: number, total: number) {
return total > 0 ? ((value / total) * 100).toFixed(1) : '0.0';
}
let search = $state('');
let showUnobtainable = $state(false);
let pageNumber = $state(1);
const pageSize = 25;
const filteredPokemon = $derived(
data.pokemon.filter((pokemon) => {
const availability =
viewGameId === null ? undefined : entryMap.get(pokemon.id)?.get(viewGameId)?.availability;
if (
!showUnobtainable &&
viewGameId !== null &&
!(availability && obtainableAvailability.has(availability))
)
return false;
return `${pokemon.number} ${pokemon.name}`
.toLowerCase()
.includes(search.trim().toLowerCase());
})
);
const pageCount = $derived(Math.max(1, Math.ceil(filteredPokemon.length / pageSize)));
$effect(() => {
if (pageNumber > pageCount) pageNumber = pageCount;
});
const visiblePokemon = $derived(
filteredPokemon.slice((pageNumber - 1) * pageSize, pageNumber * pageSize)
);
const gamesByGeneration = $derived(
[...Map.groupBy(data.games, (game) => game.generation)].sort(([a], [b]) => a - b)
);
let rulesDialog: HTMLDialogElement;
const draft = new SvelteSet<number>();
const generations = $derived([...Map.groupBy(data.games, (g) => g.generation)]);
function openRules() {
draft.clear();
for (const id of data.gamesConfigured ? selectedGameIds : data.games.map((game) => game.id))
draft.add(id);
rulesDialog.showModal();
}
function tooltip(entry: Entry | undefined, game: Game): string | null {
if (!entry) return `No catalog record for ${game.name}; availability is not confirmed`;
if (obtainableAvailability.has(entry.availability)) return null;
const reason = {
trade_only: 'Only obtainable by trading in this game',
transfer_only: 'Only obtainable by transferring from another game',
event_only: 'Only obtainable through an event distribution',
unknown: 'Availability has not been confirmed'
}[entry.availability as 'trade_only' | 'transfer_only' | 'event_only' | 'unknown'];
return entry.note ? `${reason} (${entry.note})` : reason;
}
let detailsDialog: HTMLDialogElement;
let detailNumber = $state<number | null>(null);
function openDetails(number: number) {
detailNumber = number;
detailsDialog.showModal();
for (const game of data.games)
if (!data.gamesConfigured || data.selectedGameIds.includes(game.id)) draft.add(game.id);
rulesOpen = true;
}
</script>
<div class="mx-auto max-w-6xl px-4 py-10 sm:px-6 sm:py-14">
<a
href={resolve('/projects/game-tracker')}
class="text-[var(--site-muted)] hover:text-[var(--site-text)]">← game tracker</a
<div class="mx-auto max-w-[1600px] px-3 py-4 sm:px-5">
<div
class="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2 lg:grid-cols-[auto_minmax(0,1fr)_auto]"
>
<div class="mt-3 flex flex-wrap items-end justify-between gap-5">
<div>
<h1 class="text-4xl font-semibold tracking-tight sm:text-5xl">catchemall</h1>
<p class="mt-2 text-[var(--site-muted)]">
{data.pokemon.length} Pokémon · {data.games.length} games
</p>
</div>
<Button variant="outline" type="button" onclick={openRules}>set rules</Button>
</div>
{#if !data.user}<p class="mt-6">
<a
href={resolve('/login?returnTo=/projects/game-tracker/pokemon')}
class="underline underline-offset-4">sign in</a
> to save your progress.
</p>{/if}
{#if saveError}<p role="alert" class="mt-5 text-red-500">{saveError}</p>{/if}
{#if !data.pokemon.length}<p class="mt-8 text-[var(--site-muted)]">
the Pokémon catalog has not been loaded yet.
</p>{/if}
<div class="mt-8 border-y border-[var(--site-border)] py-6">
<div class="flex flex-wrap items-baseline justify-between gap-2">
<p class="font-medium">overall progress</p>
<p class="text-2xl font-semibold tabular-nums">
{percent(progress.caughtEntries, progress.catchableEntries)}%
</p>
</div>
<div class="mt-3">
<ProgressBar
value={progress.caughtEntries}
max={progress.catchableEntries}
label="Overall catch progress"
/>
</div>
<p class="mt-2 text-base text-[var(--site-muted)]">
{progress.caughtEntries} of {progress.catchableEntries} obtainable entries caught
</p>
<div class="mt-8 grid gap-x-10 gap-y-7 lg:grid-cols-3">
{#each progressBars as item (item.label)}
<div class="min-w-0">
<div class="flex flex-wrap items-baseline justify-between gap-2">
<p class="font-medium">{item.label}</p>
<p class="text-xl font-semibold tabular-nums">{percent(item.value, item.total)}%</p>
</div>
<div class="mt-3">
<ProgressBar value={item.value} max={item.total} label={item.label} small />
</div>
<p class="mt-2 text-base text-[var(--site-muted)]">
{item.value} of {item.total}
{item.unit}
</p>
</div>
{/each}
</div>
<p class="mt-6 text-base text-[var(--site-muted)]">
counts use your selected games. Pokémon you can evolve or breed there count as obtainable.
</p>
</div>
<div class="mt-8 grid gap-4 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<label class="block"
>search Pokémon
<Input
type="search"
bind:value={search}
oninput={() => (pageNumber = 1)}
placeholder="name or number"
class="mt-2 h-11"
/>
</label>
<label class="block"
>game
<select
bind:value={viewGameId}
onchange={() => (pageNumber = 1)}
disabled={!visibleGames.length}
class="mt-2 block w-full rounded border border-[var(--site-border)] bg-[var(--site-bg)] px-3 py-3"
>
{#each visibleGames as game (game.id)}<option value={game.id}>{game.name}</option>{/each}
</select>
</label>
</div>
<div class="mt-5 flex flex-wrap items-center justify-between gap-4">
<label class="flex cursor-pointer items-center gap-3">
<input
type="checkbox"
checked={showUnobtainable}
onchange={(event) => {
showUnobtainable = event.currentTarget.checked;
pageNumber = 1;
}}
class="h-5 w-5 accent-[var(--site-text)]"
/>
show Pokémon you can’t get in this game
</label>
<a
href={resolve('/projects/game-tracker/pokemon/locations')}
class="underline underline-offset-4">browse locations</a
>
</div>
{#if viewGame}
<div class="mt-8">
<table class="w-full table-fixed border-collapse">
<colgroup><col /><col class="w-24 sm:w-36" /></colgroup>
<thead
><tr class="border-b border-[var(--site-border)] text-left text-[var(--site-muted)]"
><th scope="col" class="py-3 font-medium">Pokémon</th><th
scope="col"
class="py-3 text-center font-medium">caught</th
></tr
></thead
<div class="flex items-center gap-3">
{#if data.activeGame}<GameLogo
slug={`pokemon/${data.activeGame.slug}`}
name={data.activeGame.name}
class="h-12 w-12"
/>{/if}
<div>
<a
href={resolve('/projects/game-tracker')}
class="text-xs text-muted-foreground hover:underline">← Game tracker</a
>
<tbody>
{#each visiblePokemon as pokemon (pokemon.id)}
{@const entry = entryMap.get(pokemon.id)?.get(viewGame.id)}
{@const reason = tooltip(entry, viewGame)}
<tr class="border-b border-[var(--site-border)]">
<th scope="row" class="py-2 text-left font-normal">
<button
type="button"
onclick={() => openDetails(pokemon.number)}
class="flex w-full min-w-0 items-center gap-3 text-left hover:text-[var(--site-muted)]"
>
<img
src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/{pokemon.number}.png"
alt=""
loading="lazy"
width="40"
height="40"
class="h-10 w-10 shrink-0"
/>
<span class="min-w-0"
><span class="mr-2 text-[var(--site-muted)]">#{pokemon.number}</span
>{pokemon.name}
{#if entry && reason === null}<span
class="block truncate text-sm text-[var(--site-muted)]"
>{availabilityLabels[entry.availability]}{entry.note
? ` · ${entry.note}`
: ''}</span
>{/if}</span
>
</button>
</th>
<td class="py-2 text-center">
{#if entry && reason === null}
<input
type="checkbox"
class="h-5 w-5 cursor-pointer accent-[var(--site-text)]"
checked={caught.has(entry.id)}
disabled={!hydrated || !data.user || pending.has(entry.id)}
aria-label={`Caught ${pokemon.name} in ${viewGame.name}`}
title={data.user ? (entry.note ?? undefined) : 'Sign in to save your progress'}
onchange={(event) => toggleCaught(entry.id, event.currentTarget.checked)}
/>
{:else}
<span
title={reason ?? undefined}
aria-label={`${pokemon.name} in ${viewGame.name}: ${reason}`}
class="text-[var(--site-muted)]"
>{!entry ? '—' : entry.availability === 'unknown' ? '?' : '·'}</span
>
{/if}
</td>
</tr>
{:else}
<tr><td colspan="2" class="py-8 text-[var(--site-muted)]">no Pokémon found</td></tr>
{/each}
</tbody>
</table>
<div class="mt-5 flex flex-wrap items-center justify-between gap-4">
<p class="text-[var(--site-muted)]">
{filteredPokemon.length ? (pageNumber - 1) * pageSize + 1 : 0}–{Math.min(
pageNumber * pageSize,
filteredPokemon.length
)} of {filteredPokemon.length}
</p>
<div class="flex items-center gap-4">
<Button
variant="outline"
size="sm"
type="button"
disabled={pageNumber === 1}
onclick={() => (pageNumber -= 1)}>previous</Button
<h1 class="text-xl font-semibold">
Pokémon journal <span class="text-sm font-normal text-muted-foreground"
>· {data.activeGame?.name ?? 'Choose a game'}</span
>
<span class="text-[var(--site-muted)]">{pageNumber}/{pageCount}</span>
<Button
variant="outline"
size="sm"
type="button"
disabled={pageNumber === pageCount}
onclick={() => (pageNumber += 1)}>next</Button
>
</div>
</h1>
</div>
</div>
{:else if data.pokemon.length}
<p class="mt-8 text-[var(--site-muted)]">no games selected. use “set rules” to choose one.</p>
{/if}
<div
class={`game-covers order-3 col-span-2 overflow-x-auto pb-1 ${visibleGames.length > 30 ? 'lg:col-span-3' : 'lg:order-none lg:col-span-1'}`}
bind:clientWidth={stripWidth}
role="group"
aria-label="Choose Pokémon game"
>
<div
class="grid gap-1"
style:grid-template-columns={`repeat(${Math.max(1, Math.ceil(visibleGames.length / coverRows))}, minmax(40px, 1fr))`}
style:max-width={`${Math.ceil(visibleGames.length / coverRows) * 64}px`}
>
{#each visibleGames as game (game.id)}
<Button
variant="ghost"
disabled={!hydrated}
aria-pressed={data.activeGame?.id === game.id}
aria-label={`Play ${game.name}`}
title={game.name}
class={`game-cover-button h-12 min-w-0 rounded-md border p-1 ${data.activeGame?.id === game.id ? 'border-amber-500 bg-amber-500/15 ring-1 ring-amber-500' : 'border-transparent opacity-65 hover:opacity-100'}`}
onclick={() =>
goto(resolve(`/projects/game-tracker/pokemon?game=${game.slug ?? game.id}`), {
noScroll: true,
keepFocus: true
})}
>
<GameLogo slug={`pokemon/${game.slug}`} name={game.name} class="h-10 w-full" />
</Button>
{/each}
</div>
</div>
<Button
class="justify-self-end lg:col-start-3"
variant="ghost"
size="sm"
disabled={!hydrated}
onclick={openRules}>set rules</Button
>
</div>
<details class="mt-10 border-t border-[var(--site-border)] pt-5 text-[var(--site-muted)]">
<summary class="cursor-pointer">about availability</summary>
<p class="mt-3 max-w-3xl">
the catalog is owned by this site and built from a pinned PokéAPI snapshot. Checkboxes appear
for Pokémon you can catch (wild, gift, static or in-game trade), evolve from something you can
get in that game, or breed. “·” marks event-only mythicals, “?” means the Pokémon is in the
game but no route is confirmed, and “—” means there is no record. Neither proves it is
unobtainable. Newer games (Brilliant Diamond and later) have no encounter data yet.
</p>
</details>
{#if !data.user}<p class="mt-4 text-sm">
<a href={resolve('/login?returnTo=/projects/game-tracker/pokemon')} class="underline"
>Sign in</a
> to save catches, teams and adventures.
</p>{/if}
{#if form?.message && !rulesOpen}<p role="alert" class="mt-4 text-destructive">
{form.message}
</p>{/if}
{#if data.activeGame}{#key data.activeGame.id}<PokemonJournal {data} />{/key}{:else}<p
class="mt-8 text-muted-foreground"
>
No games selected. Use “set rules” to choose your next adventure.
</p>{/if}
<p class="mt-4 text-[10px] leading-relaxed text-muted-foreground">
Species, regional Pokédexes, moves and encounters from <a
href="https://pokeapi.co/"
class="underline">PokéAPI</a
>. Encounter coverage varies by game; missing records do not prove that a Pokémon is
unavailable. Stats and move battle values describe the catalog’s default forms and current
snapshot. Maps identify their source and coverage.
</p>
</div>
<dialog
bind:this={detailsDialog}
onclose={() => (detailNumber = null)}
class="m-auto max-h-[90vh] w-[calc(100%-2rem)] max-w-2xl overflow-y-auto rounded-xl border border-[var(--site-border)] bg-[var(--site-surface)] p-5 text-[var(--site-text)] backdrop:bg-black/70 sm:p-6"
>
<div class="flex justify-end">
<button type="button" onclick={() => detailsDialog.close()} class="text-[var(--site-muted)]"
>close</button
<Dialog.Root bind:open={rulesOpen}>
<Dialog.Content class="max-h-[90dvh] overflow-y-auto sm:max-w-3xl">
<Dialog.Header
><Dialog.Title>Set rules</Dialog.Title><Dialog.Description
>Choose the games in your collection. Your saved catches stay with each game.</Dialog.Description
></Dialog.Header
>
</div>
{#if detailNumber !== null}
<PokemonDetails
number={detailNumber}
gameId={viewGameId}
isAdmin={data.isAdmin}
onsaved={() => invalidateAll()}
/>
{/if}
</dialog>
<dialog
bind:this={rulesDialog}
class="m-auto w-[calc(100%-2rem)] max-w-2xl rounded-xl border border-[var(--site-border)] bg-[var(--site-surface)] p-5 text-[var(--site-text)] backdrop:bg-black/70 sm:p-6"
>
<h2 class="text-2xl font-semibold">set rules</h2>
<p class="mt-2 text-[var(--site-muted)]">choose the games that count toward your progress.</p>
{#if form?.message}<p role="alert" class="mt-3 text-red-500">{form.message}</p>{/if}
<div class="mt-5 flex gap-5">
<button
type="button"
onclick={() => {
draft.clear();
for (const game of data.games) draft.add(game.id);
{#if form?.message}<p role="alert" class="text-destructive">{form.message}</p>{/if}
<div class="flex gap-2">
<Button
variant="outline"
size="sm"
onclick={() => {
for (const game of data.games) draft.add(game.id);
}}>Select all</Button
><Button variant="ghost" size="sm" onclick={() => draft.clear()}>Clear selection</Button>
</div>
<form
method="POST"
action="?/setGames"
use:enhance={() => {
saving = true;
return async ({ result, update }) => {
await update();
saving = false;
if (result.type === 'success') rulesOpen = false;
};
}}
class="underline underline-offset-4">all</button
>
<button type="button" onclick={() => draft.clear()} class="underline underline-offset-4"
>none</button
>
</div>
<form
method="POST"
action="?/setGames"
use:enhance={() => {
return async ({ result, update }) => {
await update();
if (result.type === 'success') rulesDialog.close();
};
}}
>
<div class="mt-5 grid max-h-[50vh] gap-5 overflow-y-auto pr-2 sm:grid-cols-2">
{#each gamesByGeneration as [generation, games] (generation)}
<fieldset>
<legend class="mb-2 font-semibold"
><label class="flex items-center gap-2"
><input
type="checkbox"
checked={games.every((game) => draft.has(game.id))}
onchange={(event) => {
for (const game of games) {
if (event.currentTarget.checked) draft.add(game.id);
else draft.delete(game.id);
}
}}
/>generation {generation}</label
></legend
>
{#each games as game (game.id)}<label class="flex items-center gap-2 py-1 pl-5"
><input
type="checkbox"
name="gameIds"
value={game.id}
checked={draft.has(game.id)}
onchange={(event) => {
if (event.currentTarget.checked) draft.add(game.id);
else draft.delete(game.id);
}}
/>{game.name}</label
>{/each}
</fieldset>
{/each}
</div>
<div class="mt-6 flex justify-end gap-5">
<button type="button" onclick={() => rulesDialog.close()}>cancel</button>
<button
disabled={!data.user}
title={data.user ? undefined : 'Sign in to save rules'}
class="rounded bg-[var(--site-text)] px-4 py-2 font-semibold text-[var(--site-bg)] disabled:opacity-40"
>save</button
<div class="grid max-h-[55dvh] gap-6 overflow-auto pr-2 sm:grid-cols-2">
{#each generations as [generation, games] (generation)}
<fieldset>
<legend class="mb-3"
><label class="flex items-center gap-2 font-semibold"
><Checkbox
checked={games.every((g) => draft.has(g.id))}
indeterminate={games.some((g) => draft.has(g.id)) &&
!games.every((g) => draft.has(g.id))}
onCheckedChange={(checked) => {
for (const g of games)
if (checked) draft.add(g.id);
else draft.delete(g.id);
}}
/>Generation {generation}</label
></legend
>
<div class="space-y-2">
{#each games as g (g.id)}<label class="flex items-center gap-3 rounded-lg border p-2"
><Checkbox
name="gameIds"
value={String(g.id)}
checked={draft.has(g.id)}
onCheckedChange={(checked) => (checked ? draft.add(g.id) : draft.delete(g.id))}
/><GameLogo slug={`pokemon/${g.slug}`} name={g.name} class="h-8 w-16" /><span
class="text-sm">{g.name}</span
></label
>{/each}
</div>
</fieldset>{/each}
</div>
<Dialog.Footer class="mt-6"
><Button variant="outline" onclick={() => (rulesOpen = false)}>Cancel</Button><Button
type="submit"
disabled={!data.user || saving}>{saving ? 'Saving…' : 'Save rules'}</Button
></Dialog.Footer
>
</div>
</form>
</dialog>
</form>
</Dialog.Content>
</Dialog.Root>

View File

@@ -0,0 +1,32 @@
import { json, error } from '@sveltejs/kit';
import { and, asc, eq } from 'drizzle-orm';
import { db } from '$lib/server/db';
import { pokemon, pokemonEncounters } from '$lib/server/db/schema';
export async function GET({ url }) {
const gameId = Number(url.searchParams.get('game'));
const locationId = Number(url.searchParams.get('location'));
if (![gameId, locationId].every((n) => Number.isSafeInteger(n) && n > 0 && n <= 2147483647))
error(400, 'Invalid game or location');
const rows = await db
.select({
pokemonId: pokemon.id,
number: pokemon.number,
name: pokemon.name,
type1: pokemon.type1,
type2: pokemon.type2,
area: pokemonEncounters.area,
method: pokemonEncounters.method,
minLevel: pokemonEncounters.minLevel,
maxLevel: pokemonEncounters.maxLevel,
rarity: pokemonEncounters.rarity,
conditions: pokemonEncounters.conditions,
form: pokemonEncounters.form,
note: pokemonEncounters.note
})
.from(pokemonEncounters)
.innerJoin(pokemon, eq(pokemon.id, pokemonEncounters.pokemonId))
.where(and(eq(pokemonEncounters.gameId, gameId), eq(pokemonEncounters.locationId, locationId)))
.orderBy(asc(pokemon.number), asc(pokemonEncounters.method), asc(pokemonEncounters.minLevel));
return json(rows, { headers: { 'Cache-Control': 'public, max-age=3600' } });
}

View File

@@ -1,4 +1,5 @@
<script lang="ts">
import { NativeSelect } from '$lib/components/ui/native-select/index.js';
import { resolve } from '$app/paths';
import { Input } from '$lib/components/ui/input/index.js';
import * as Card from '$lib/components/ui/card/index.js';
@@ -39,13 +40,13 @@
</label>
<label class="block"
>region
<select
<NativeSelect
bind:value={region}
class="mt-2 block w-full rounded border border-[var(--site-border)] bg-[var(--site-bg)] px-3 py-3"
>
<option value="">all regions</option>
{#each regions as name (name)}<option value={name}>{name}</option>{/each}
</select>
</NativeSelect>
</label>
</div>
<label class="mt-5 flex cursor-pointer items-center gap-3">

View File

@@ -1,4 +1,6 @@
<script lang="ts">
import { pokemonImage } from '$lib/game-tracker/game-art';
import { NativeSelect } from '$lib/components/ui/native-select/index.js';
import { resolve } from '$app/paths';
import { enhance } from '$app/forms';
import { page } from '$app/state';
@@ -124,12 +126,12 @@
{#if games.length}
<label class="block"
>game
<select
<NativeSelect
bind:value={gameId}
class="mt-2 block rounded border border-[var(--site-border)] bg-[var(--site-bg)] px-3 py-2"
>
{#each games as [id, name] (id)}<option value={id}>{name}</option>{/each}
</select>
</NativeSelect>
</label>
{/if}
</div>
@@ -139,7 +141,7 @@
{#each list as encounter, index (index)}
<li class="flex items-center gap-3 border-t border-[var(--site-border)] py-2">
<img
src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/{encounter.number}.png"
src={pokemonImage(encounter.number)}
alt=""
loading="lazy"
width="40"