feat: add leaderboard sort toggle with SSR-safe preference persistence

Merged
JU
10mo ago
+419-239

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 Switch component with Tokens/Cost labels
  • Memoized LeaderboardRow for smooth toggling
  • Replaced all inline style={{}} with styled-components
  • Uses initialSortBy prop to prevent hydration mismatch

API (/api/leaderboard, /api/leaderboard/user/[username])

  • Added sortBy query parameter (tokens | cost)
  • Dynamic ORDER BY clause in getLeaderboard.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.ts for server/client

Commits

  1. b43eb9f - feat: add leaderboard sort toggle UI
  2. e8163d5 - perf: memoize LeaderboardRow for faster toggle
  3. f4c8015 - feat(api): add server-side sortBy param
  4. 7f627ec - fix: add type="button", validate localStorage
  5. 6ab1212 - refactor: replace inline styles with styled-components
  6. f21be27 - fix(ssr): use cookie for sortBy preference
  7. 7c1d24e - 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