feat: add leaderboard sort toggle with SSR-safe preference persistence
Merged
JU
10mo ago+419+419+012345678901234567890123456789-239-239-012345678901234567890123456789
Summary
Add a toggle to sort the leaderboard by Tokens or Cost, with server-side sorting for correct global rankings and SSR-safe preference persistence via Suspense streaming.
Features
- Toggle UI: Blue switch component to choose between Tokens/Cost sorting
- Server-side sorting: Correct global rankings across paginated results
- Preference persistence: Saves to localStorage + syncs to cookie
- No flash on reload: Suspense streams personalized content after static shell
Architecture
┌─────────────────────────────────────┐
│ Static Shell (instant) │
│ ┌─────────────────────────────┐ │
│ │ Navigation │ │
│ │ BlackholeHero │ │
│ └─────────────────────────────┘ │
│ ┌─────────────────────────────┐ │
│ │ <Suspense fallback> │ │
│ │ ┌───────────────────┐ │ │
│ │ │ LeaderboardSkeleton│ │ │
│ │ └───────────────────┘ │ │
│ │ ↓ streams in │ │
│ │ ┌───────────────────┐ │ │
│ │ │ LeaderboardClient │ │ │ ← reads cookie, fetches with sortBy
│ │ └───────────────────┘ │ │
│ └─────────────────────────────┘ │
│ ┌─────────────────────────────┐ │
│ │ Footer │ │
│ └─────────────────────────────┘ │
└─────────────────────────────────────┘
Changes
UI (LeaderboardClient.tsx)
- New
Switchcomponent with Tokens/Cost labels - Memoized
LeaderboardRowfor smooth toggling - Replaced all inline
style={{}}with styled-components - Uses
initialSortByprop to prevent hydration mismatch
API (/api/leaderboard, /api/leaderboard/user/[username])
- Added
sortByquery parameter (tokens|cost) - Dynamic
ORDER BYclause ingetLeaderboard.ts - User rank calculated based on selected sort metric
SSR (page.tsx, useSettings.ts, constants.ts)
- Wrapped leaderboard in
<Suspense>for streaming - Cookie reading inside Suspense boundary (preserves static shell)
- Client syncs localStorage to cookie on preference change
- Shared validation in
constants.tsfor server/client
Commits
b43eb9f- feat: add leaderboard sort toggle UIe8163d5- perf: memoize LeaderboardRow for faster togglef4c8015- feat(api): add server-side sortBy param7f627ec- fix: add type="button", validate localStorage6ab1212- refactor: replace inline styles with styled-componentsf21be27- fix(ssr): use cookie for sortBy preference7c1d24e- refactor(ssr): use Suspense for personalized content
Testing
- Toggle switches between tokens/cost sorting instantly
- Rankings are globally correct
- Preference persists across page navigation
- Static shell loads instantly, leaderboard streams in
- No flash on hard reload