diff --git a/docs/design-system.md b/docs/design-system.md index ad898a2..e90ca82 100644 --- a/docs/design-system.md +++ b/docs/design-system.md @@ -2,8 +2,8 @@ One visual language that every page is built from, so pages can't drift apart. See it all at `/dev/ui` (dev builds only). ## Direction -"Navy", chosen by the lead on 2026-10-19 (reference: `design/reference.webp`, a direction, not a target). -- Dark blue slate, never pitch black. One cyan accent; at most one primary button per view. +"Classic" (2026-11-07): the old sourcejump.net, updated. Replaced "Navy". +- A slate sheet (`bg`, `shadow-sheet`) between darker gutters. One cyan accent; at most one primary button per view. - Gamified but professional: medals, tier colors, WR badges, count-ups and small motions. No mascots, confetti, slogans or sales copy. - Play for everything. Its digits are all the same width, so times line up in columns without a second font. - Corners: `rounded-sm` (4px) for badges, `rounded-md` (8px) for controls and rows, `rounded-lg` (12px) only for padded cards and dialogs. @@ -21,6 +21,7 @@ One visual language that every page is built from, so pages can't drift apart. S | Component | Use | |---|---| | `Page` | Every page's content area; `width` is `wide`, `narrow` (reading) or `fill` (inside a section layout that sets its own width, such as the staff area). Runs the page fade | +| `Masthead` | Full-width top band, plain or over a map picture; inside `Page width="fill"` (Players pages) | | `Link` | Every internal link; never prefetches. Lint blocks importing `next/link` elsewhere | | `Button`, `ButtonLink`, `ButtonAnchor` | `primary` (one per view), `secondary` (default), `ghost`; sizes `sm`, `md`. A `ghost` button with `aria-pressed` or `aria-expanded` shows the accent while on. `ButtonAnchor` is for full page loads, such as sign-in | | `Card`, `Label` | Bordered surface; `interactive` adds the hover lift. `Label` is the small uppercase heading | @@ -36,7 +37,7 @@ One visual language that every page is built from, so pages can't drift apart. S | `Segmented` | Looks like segmented `Tabs`, for a choice that changes the view in place (a server's activity range, a post's kind). The chosen option is in the accent | | `ChoiceMenu` | "Label Value ▾": one choice from a list, in a `Menu` of radio items, changing the view in place, or following each option's `href` on a server page. Boards, profiles and the Maps page use a row of them (Style, Track, Runs; Sort, Records in; lead, 2026-10-26); quiet options are dimmed but choosable, disabled ones dimmed and kept in place. On a phone each takes a full row, label left and value right | | `ChoiceBar` | The row those menus sit in, with any tabs beside them. Every page uses it, so the spacing between choices stays the same everywhere | -| `Pager` | Previous and next under a paged list | +| `Pager` | Previous and next under a paged list; `param`: its address key | | `DividedList`, `DividedSection` | Rows with lines between them, and a part set off by a line above, inside a `Card` or `Dialog`. The lines run to the surface's edges | | `StepChart` | A value that changes in steps over time (WR history). Hover snaps a crosshair to the nearest point; points take focus and open their link | | `LineChart` | One count over time from zero (players online). Drawn in a fixed box stretched by CSS, so it fills its container before scripts load. Hover, tap or arrow keys pick a point; the parent shows its values. An optional second line (`y2`, gold) shows a part of the first on the same scale (world records among runs). Never two scales on one chart | @@ -44,7 +45,8 @@ One visual language that every page is built from, so pages can't drift apart. S | `Tooltip` | Hint on hover and focus; the child must be focusable | | `Menu`, `MenuItem`, `MenuLink`, `MenuSeparator` | Menu button (account, mobile sections) | | `Dialog` | Controlled modal (`open`, `onClose`). A field marked `data-autofocus` takes focus on each opening (React's `autoFocus` fires only on mount). Closes itself, without calling `onClose`, when its page is hidden for Back | -| `Input`, `Textarea`, `CountUp` | Text field with optional icon; multi-line field; animated number | +| `BrandIcon`, `SteamButton` | Community and Steam logos (`colored`: in their own colors); Steam sign-in | +| `Input`, `SearchField`, `Textarea`, `CountUp` | Text field with optional icon; search, button inside; multi-line field; animated number | | `Prose` | Long-form HTML (a post's body) in the site's type. Only for HTML the API made safe | The run dialog opens in place: `RunLink` adds `?run=` to the address with `history.pushState`, and `RunDialogHost` (in the root layout) opens at once and loads the run inside. Back or Escape closes it, and the address can be shared. A run link's `href` is `/runs/{id}`, the run's own page, for new tabs. A map page's style and track work the same way, with `replaceState`. @@ -63,7 +65,6 @@ Named utilities, so pages never write their own transitions: - `motion-reveal`: a section rising in as it scrolls into view (scroll-driven; browsers without it show it at once). - `motion-settle`: a large picture easing out of a slight zoom as the page opens (the home header). - `HeaderDepth` (`features/home/`): the home header's picture leans with the mouse, by a depth map of it (`scripts/header-depth.py`; rerun it when the picture changes). Dust drifts in the light shaft, and a click sends cyan traces crawling over the surfaces (`headerTraces.ts`). WebGL, running only while the header is on screen; off on touch screens and with reduced motion. -- `motion-ripple`: a ring spreading and fading from where something landed; re-key it to replay. - `motion-pop`: a popover menu fading in with a slight drop and grow, and fading out as it closes (`Menu`). - `CountUp`: counts up when scrolled into view, and from the old value when it changes. A number already in view when the page loads stays as it is. - `page-fade`: between pages (see Navigation). @@ -76,7 +77,7 @@ Pages swap in place with no full page load. The old page fades out quickly and t Links never prefetch, whether in view or hovered (lead's choice, 2026-10-19). A page loads only once it's opened, and the fade covers the wait. `e2e/navigation.e2e.ts` checks that following a link doesn't reload the page. ## Layout shell (`web/src/features/site/`) -Header (wordmark, sections, account corner) and footer, applied in the root layout. On narrow screens the sections collapse into a menu. The account corner (sign-in button, or the player's menu) and the current-section highlight depend on the request, so each sits in `` and every page's shell stays static. Search lives on the Players page. Section pages arrive with their roadmap slices. +Header, page and footer sit on the sheet. The header is one sticky bar: wordmark, sections, search (`/`), Steam sign-in; footer: one line, community logos. Phones: menu, wordmark, search, account. Account and current section sit in ``, so every shell stays static. Search lives on the Players page. Section pages arrive with their roadmap slices. ## Screenshot tests `npm run test:ui` (part of `just check`) screenshots `/dev/ui` wide, on a phone, with the menu open and with the dialog open, and fails on any pixel change. After an intended visual change: diff --git a/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png index 626adf1..d1620a6 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/desktop-chrome-linux.png differ diff --git a/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png index 7d042cf..eab279a 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/dialog-chrome-linux.png differ diff --git a/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png index e100367..7f40452 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/menu-chrome-linux.png differ diff --git a/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png b/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png index de65fcc..80fef9e 100644 Binary files a/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png and b/web/e2e/style-guide.e2e.ts-snapshots/phone-chrome-linux.png differ diff --git a/web/src/app/globals.css b/web/src/app/globals.css index 8bdcfec..3fc3984 100644 --- a/web/src/app/globals.css +++ b/web/src/app/globals.css @@ -12,8 +12,9 @@ cursor: pointer; } + /* The window either side of the sheet; pages sit on the sheet (the root layout). */ body { - background: var(--color-bg); + background: var(--color-gutter); color: var(--color-text); font-family: var(--font-sans); font-size: var(--text-base); diff --git a/web/src/app/layout.tsx b/web/src/app/layout.tsx index 07418f3..cc3b04a 100644 --- a/web/src/app/layout.tsx +++ b/web/src/app/layout.tsx @@ -1,7 +1,9 @@ // Root layout: fonts, global styles, the header and footer, the run dialog, and site-wide metadata. import type { Metadata } from "next"; +import Image from "next/image"; import { Play } from "next/font/google"; import { Suspense } from "react"; +import art from "@/features/site/header-interloper.webp"; import { RunDialogHost } from "@/features/runs/RunDialogHost"; import { SiteFooter } from "@/features/site/SiteFooter"; import { SiteHeader } from "@/features/site/SiteHeader"; @@ -28,14 +30,33 @@ export default function RootLayout({ children }: LayoutProps<"/">) { - {/* The header and page fill at least the window, so the footer starts right at the fold: the page - always scrolls, and the scrollbar doesn't come and go between short and long pages. The space - above the footer is padding in here, not a margin on the footer, so it doesn't push it lower. */} -
- -
{children}
+ {/* What shows in the gutters either side of the sheet: the header's map picture, blurred and darkened + far back, fixed while the page scrolls. Blurred anyway, so a small copy of it is plenty. */} +
+ +
+
+ {/* The sheet, as the old sourcejump.net had it: one column down the middle of the window, edges lit, + holding the header, the page and the footer, the gutters either side. */} +
+ {/* The header and page fill at least the window, so the footer starts right at the fold: the page + always scrolls, and the scrollbar doesn't come and go between short and long pages. The space + above the footer is padding in here, not a margin on the footer, so it doesn't push it lower. */} +
+ +
{children}
+
+
- {/* The run dialog, over whichever page opened it (`?run=` in the address). */} diff --git a/web/src/app/leaderboards/[ranking]/page.tsx b/web/src/app/leaderboards/[ranking]/page.tsx index a8f5854..ccedbc6 100644 --- a/web/src/app/leaderboards/[ranking]/page.tsx +++ b/web/src/app/leaderboards/[ranking]/page.tsx @@ -31,7 +31,7 @@ export default function LeaderboardListPage({ return ( {Promise.all([params, searchParams]).then( - ([{ ranking }, { style, track, view }]) => { + ([{ ranking }, { style, track, view, page }]) => { if (!rankings.includes(ranking)) notFound(); return ( ); }, diff --git a/web/src/app/leaderboards/page.tsx b/web/src/app/leaderboards/page.tsx index 4c706ff..80efa69 100644 --- a/web/src/app/leaderboards/page.tsx +++ b/web/src/app/leaderboards/page.tsx @@ -1,4 +1,5 @@ -// Leaderboards page: the top players by points and by completions, per style and track, and pre-2.0. +// Leaderboards page: the top players by points and by completions, per style and track, and pre-2.0, each list +// paged on its own. import type { Metadata } from "next"; import { Leaderboards } from "@/features/leaderboards/Leaderboards"; import { Page } from "@/ui/Page"; @@ -12,17 +13,24 @@ export default function LeaderboardsPage({ searchParams, }: PageProps<"/leaderboards">) { return ( - +

Leaderboards

- {searchParams.then(({ style, track, view }) => ( - - ))} + {searchParams.then( + ({ style, track, view, points_page, completed_page }) => ( + + ), + )}
); } diff --git a/web/src/app/page.tsx b/web/src/app/page.tsx index 6c77803..f005dac 100644 --- a/web/src/app/page.tsx +++ b/web/src/app/page.tsx @@ -1,16 +1,13 @@ -// Home page: the site's header, what bunnyhopping is, how to start, and the latest records and servers. -import { BhopIntro } from "@/features/home/BhopIntro"; -import { GetStarted } from "@/features/home/GetStarted"; +// Home page: the site's header with the way in, then what's happening now: how busy SourceJump is, the newest +// world records beside the top players, and the servers people are playing on. import { HomeHeader } from "@/features/home/HomeHeader"; import { LiveNow } from "@/features/home/LiveNow"; import { Page } from "@/ui/Page"; export default function HomePage() { return ( - + - - ); diff --git a/web/src/app/players/[steamid]/layout.tsx b/web/src/app/players/[steamid]/layout.tsx index df86c5f..9df8188 100644 --- a/web/src/app/players/[steamid]/layout.tsx +++ b/web/src/app/players/[steamid]/layout.tsx @@ -1,4 +1,4 @@ -// A player's pages: the header stays while the profile and the Manage view swap beneath it. +// A player's pages: the masthead stays while the profile and the Manage view swap beneath it. import { PlayerHeader } from "@/features/players/PlayerHeader"; import { Page } from "@/ui/Page"; @@ -7,11 +7,14 @@ export default function PlayerLayout({ children, }: LayoutProps<"/players/[steamid]">) { return ( - + // The masthead runs edge to edge, so the page sets its own width below it. + {params.then(({ steamid }) => ( ))} - {children} +
+ {children} +
); } diff --git a/web/src/app/players/page.tsx b/web/src/app/players/page.tsx index 37fc7ce..6ee8c31 100644 --- a/web/src/app/players/page.tsx +++ b/web/src/app/players/page.tsx @@ -1,8 +1,11 @@ -// Players page: how many players have a recorded time over time, search by name or SteamID, and recently -// active players; for staff, a Banned tab. +// Players page, laid out as the other boards: the title with how many players have a recorded time and the search +// beside it, players found as you type or recently active in two columns, then players over time. For staff, a +// Banned tab. import type { Metadata } from "next"; +import { api } from "@/api/client"; import { DailyTotals } from "@/features/dailyTotals/DailyTotals"; -import { PlayerSearch } from "@/features/players/PlayerSearch"; +import { PlayersBoard } from "@/features/players/PlayerSearch"; +import { CountUp } from "@/ui/CountUp"; import { Page } from "@/ui/Page"; export const metadata: Metadata = { @@ -12,15 +15,41 @@ export const metadata: Metadata = { export default function PlayersPage({ searchParams }: PageProps<"/players">) { return ( - -

Players

- - {searchParams.then(({ q, view }) => ( - - ))} + + {searchParams.then(async ({ q, view }) => { + const search = typeof q === "string" ? q.trim() : ""; + const total = await playerTotal(); + return ( + <> + +

Players

+ {total != null && ( +

+ + + {" "} + players have a recorded time on SourceJump. +

+ )} +
+ } + /> + + + ); + })} ); } + +/** How many players have a recorded time; none if the totals can't be loaded. */ +async function playerTotal(): Promise { + const result = await api + .GET("/v1/daily-totals/players", { params: { query: { range: "month" } } }) + .catch(() => undefined); + return result?.data?.points.at(-1)?.players; +} diff --git a/web/src/app/sign-in/failed/page.tsx b/web/src/app/sign-in/failed/page.tsx index e4c4985..1ffcb72 100644 --- a/web/src/app/sign-in/failed/page.tsx +++ b/web/src/app/sign-in/failed/page.tsx @@ -1,7 +1,7 @@ // Where sign-in lands when Steam didn't confirm it. import type { Metadata } from "next"; -import { ButtonAnchor } from "@/ui/Button"; import { Page } from "@/ui/Page"; +import { SteamButton } from "@/ui/SteamButton"; export const metadata: Metadata = { title: "Sign-in didn't complete", @@ -16,9 +16,7 @@ export default function SignInFailedPage() { Steam didn't confirm the sign-in, or it took too long. Nothing was changed. Try again.

- - Sign in with Steam - + Sign in with Steam ); } diff --git a/web/src/features/home/BhopDemo.tsx b/web/src/features/home/BhopDemo.tsx deleted file mode 100644 index b1efc01..0000000 --- a/web/src/features/home/BhopDemo.tsx +++ /dev/null @@ -1,455 +0,0 @@ -"use client"; -// The home page's bhop demo: a simulated player hopping block to block, seen from above at an angle, with the -// keys they hold and their speed shown the way a bhop server's HUD shows them. -import { ArrowLeft, ArrowRight, Pause, Play } from "lucide-react"; -import { - useEffect, - useId, - useMemo, - useRef, - useState, - type ReactNode, -} from "react"; -import { Button } from "@/ui/Button"; -import { classNames } from "@/ui/classNames"; -import { simulateStrafes, tickSeconds, type StrafeTick } from "./strafeSim"; - -const SECONDS = 9.5; -// Once the run ends it fades out, then starts again. -const FADE_SECONDS = 0.6; -// How long the jump key stays lit after a jump, so it's visible at 60 frames a second. -const JUMP_LIT_TICKS = 12; -// With reduced motion the demo shows one still moment, late enough that several hops are behind it. -const STILL_TICK = 620; - -// The drawing, in its own units. The player stays at PLAYER_X while the course moves past, a little left of -// the middle so more of the course ahead shows than behind. The block tops sit at the middle height: the hops -// and strafes reach about as far above them as the blocks' sides reach below. -const WIDTH = 1000; -const HEIGHT = 440; -const PLAYER_X = 460; -const GROUND_Y = HEIGHT / 2; -// An oblique view: forward runs to the right, left runs up and a little right, height runs up. Height is drawn -// taller than it is, so the hops read as clearly as the strafes. -const SCALE = 0.75; -const DEPTH_X = 0.35; -const DEPTH_Y = 0.9; -const HEIGHT_Y = 1.3; -// Blocks stand on a floor this far below them; their tops are where the player lands. -const FLOOR = 48; -const BLOCK = 32; -// The floor's grid reaches further back than forward, and fades out towards the back. -const GRID = 64; -const GRID_BACK = 640; -const GRID_FRONT = 384; -// The trail keeps the last few seconds; older parts have left the drawing anyway. -const TRAIL_TICKS = 400; - -type Point = readonly [number, number]; - -/** - * Rounded to a tenth: Node and the browser can differ in a sine's last digits, and the server's drawing has to - * match the browser's exactly for React to take it over. - */ -function project(x: number, y: number, z: number): Point { - return [ - round((x + y * DEPTH_X) * SCALE), - round(-(y * DEPTH_Y + z * HEIGHT_Y) * SCALE), - ]; -} - -function round(value: number): number { - return Math.round(value * 10) / 10; -} - -function points(list: readonly Point[]): string { - return list.map(([x, y]) => `${x},${y}`).join(" "); -} - -export function BhopDemo() { - const ticks = useMemo(() => simulateStrafes(SECONDS + 1), []); - const landings = useMemo( - () => ticks.flatMap((tick, index) => (tick.jump ? [index] : [])), - [ticks], - ); - const [time, setTime] = useState(0); - const [playing, setPlaying] = useState(true); - const [still, setStill] = useState(false); - const frame = useRef(null); - - // Plays only while on screen and not paused; the browser already pauses animation frames in hidden tabs. - useEffect(() => { - if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) { - // eslint-disable-next-line react-hooks/set-state-in-effect -- read once, after hydration - setStill(true); - return; - } - const element = frame.current; - if (!element || !playing) return; - let request = 0; - let last = 0; - let visible = false; - const step = (now: number) => { - const delta = last ? Math.min((now - last) / 1000, 0.1) : 0; - last = now; - setTime((t) => { - const next = t + delta; - return next > SECONDS + FADE_SECONDS ? 0 : next; - }); - request = requestAnimationFrame(step); - }; - const observer = new IntersectionObserver(([entry]) => { - if (entry?.isIntersecting && !visible) { - visible = true; - last = 0; - request = requestAnimationFrame(step); - } else if (!entry?.isIntersecting && visible) { - visible = false; - cancelAnimationFrame(request); - } - }); - observer.observe(element); - return () => { - observer.disconnect(); - cancelAnimationFrame(request); - }; - }, [playing]); - - const shown = still ? STILL_TICK * tickSeconds : Math.min(time, SECONDS); - const exact = shown / tickSeconds; - const index = Math.min(Math.floor(exact), ticks.length - 2); - const now = lerp(ticks[index]!, ticks[index + 1]!, exact - index); - const tick = ticks[index]!; - const hop = landings.filter((landing) => landing <= index).length; - const lastLanding = landings[hop - 1] ?? 0; - const jumping = index - lastLanding < JUMP_LIT_TICKS; - const [playerX, playerY] = project(now.x, now.y, now.z); - const [shadowX, shadowY] = project(now.x, now.y, -FLOOR); - const [cameraX] = project(now.x, 0, 0); - const trail = ticks.slice(Math.max(0, index - TRAIL_TICKS), index + 1); - - // The course doesn't move relative to itself, so it's built once and the camera slides over it. - const course = useMemo( - () => , - [ticks, landings], - ); - - return ( -
- - SECONDS && !still && "opacity-0", - )} - > - - {course} - {/* Which blocks the player has landed on, and a ring where they just did. */} - {landings.slice(0, hop).map((landing) => ( - - ))} - {hop > 0 && !still && ( - - )} - project(t.x, t.y, -FLOOR)))} - fill="none" - className="stroke-accent opacity-30" - strokeWidth={2} - strokeLinecap="round" - strokeLinejoin="round" - /> - project(t.x, t.y, t.z)))} - fill="none" - className="stroke-accent opacity-20" - strokeWidth={10} - strokeLinejoin="round" - strokeLinecap="round" - /> - project(t.x, t.y, t.z)))} - fill="none" - className="stroke-accent" - strokeWidth={2.5} - strokeLinejoin="round" - strokeLinecap="round" - /> - - - - - - - - -
-
-
- W - - A - - S - D - - Jump - -
-
- - Mouse - -
- - - - - - -
-
-
-
- - Hop {Math.max(hop, 1)} - - - {Math.round(now.speed)} - - u/s - - -
-
- - {!still && ( - - )} -
- ); -} - -/** The blocks under each landing and the floor below them, in course coordinates. */ -function Course({ - ticks, - landings, -}: { - ticks: StrafeTick[]; - landings: number[]; -}) { - const fade = useId(); - const [start, end] = [-WIDTH, (ticks.at(-1)?.x ?? 0) + WIDTH * 2]; - const lines: [Point, Point][] = []; - for (let x = start; x <= end; x += GRID) { - lines.push([ - project(x, -GRID_FRONT, -FLOOR), - project(x, GRID_BACK, -FLOOR), - ]); - } - for (let y = -GRID_FRONT; y <= GRID_BACK; y += GRID) { - lines.push([project(start, y, -FLOOR), project(end, y, -FLOOR)]); - } - const [, back] = project(0, GRID_BACK, -FLOOR); - const [, middle] = project(0, 0, -FLOOR); - // The mask's own box: left alone, a mask covers only the drawing's first screenful of the course. - const [left] = project(start, -GRID_FRONT, -FLOOR); - const [right, bottom] = project(end, -GRID_FRONT, -FLOOR); - const area = { - x: left, - y: back, - width: right + GRID_BACK * DEPTH_X * SCALE - left, - height: bottom - back, - }; - // Back blocks first, so nearer ones are drawn over them. - const blocks = [...landings].sort((a, b) => ticks[b]!.y - ticks[a]!.y); - return ( - <> - {/* An alpha mask, so only the gradient's opacity counts and it needs no colour. */} - - - - - - - - - {lines.map(([[x1, y1], [x2, y2]], i) => ( - - ))} - - {blocks.map((landing) => ( - - ))} - - ); -} - -/** A block standing on the floor, its top where the player lands. The start block is a start zone. */ -function Block({ tick, start }: { tick: StrafeTick; start: boolean }) { - const size = start ? BLOCK * 2 : BLOCK; - const { x, y } = tick; - const corner = (dx: number, dy: number, z: number) => - project(x + dx * size, y + dy * size, z); - // Seen from the front and to the right: the front and right faces show, the back and left stay hidden. - const front = [ - corner(-1, -1, 0), - corner(1, -1, 0), - corner(1, -1, -FLOOR), - corner(-1, -1, -FLOOR), - ]; - const right = [ - corner(1, -1, 0), - corner(1, 1, 0), - corner(1, 1, -FLOOR), - corner(1, -1, -FLOOR), - ]; - return ( - - - - - - ); -} - -function BlockTop({ - tick, - size = BLOCK, - className, -}: { - tick: StrafeTick; - size?: number; - className: string; -}) { - const { x, y } = tick; - const top = [ - project(x - size, y - size, 0), - project(x + size, y - size, 0), - project(x + size, y + size, 0), - project(x - size, y + size, 0), - ]; - return ( - - ); -} - -/** A ring spreading from where the player just landed. */ -function Ripple({ tick }: { tick: StrafeTick }) { - const [cx, cy] = project(tick.x, tick.y, 0); - return ( - - ); -} - -function Keycap({ - on = false, - label, - className, - children, -}: { - on?: boolean; - /** For keys drawn as an icon. */ - label?: string; - className?: string; - children: ReactNode; -}) { - return ( - - {children} - - ); -} - -function lerp(a: StrafeTick, b: StrafeTick, amount: number) { - const mix = (p: number, q: number) => p + (q - p) * amount; - return { - x: mix(a.x, b.x), - y: mix(a.y, b.y), - // The jump resets height in one tick; blending across it would dip the player through the block. - z: b.jump ? a.z : mix(a.z, b.z), - speed: mix(a.speed, b.speed), - }; -} diff --git a/web/src/features/home/BhopIntro.tsx b/web/src/features/home/BhopIntro.tsx deleted file mode 100644 index a492a20..0000000 --- a/web/src/features/home/BhopIntro.tsx +++ /dev/null @@ -1,56 +0,0 @@ -// The home page's introduction to bunnyhopping: the demo, and the three things a player does in a line each. -import type { ReactNode } from "react"; -import { BhopDemo } from "./BhopDemo"; - -const steps: { title: string; body: string; keys: ReactNode }[] = [ - { - title: "Jump as you land", - body: "Same tick, no friction, no speed lost.", - keys: Jump, - }, - { - title: "Strafe in the air", - body: "Turn the mouse the way of the key you hold.", - keys: ( - <> - A - D - - ), - }, - { - title: "Chain the hops", - body: "Each hop starts with the last one's speed.", - keys: u/s, - }, -]; - -export function BhopIntro() { - return ( -
-

- Speed from jumping and strafing -

- -
    - {steps.map((step) => ( -
  1. - {step.keys} - - {step.title} - {step.body} - -
  2. - ))} -
-
- ); -} - -function Key({ children }: { children: ReactNode }) { - return ( - - {children} - - ); -} diff --git a/web/src/features/home/GetStarted.tsx b/web/src/features/home/GetStarted.tsx deleted file mode 100644 index 661292f..0000000 --- a/web/src/features/home/GetStarted.tsx +++ /dev/null @@ -1,63 +0,0 @@ -// The home page's way in for a new player: where to play, what to play, and where their times show up. -import { - Activity, - ArrowRight, - Map, - Server, - type LucideIcon, -} from "lucide-react"; -import { Card } from "@/ui/Card"; -import { Link } from "@/ui/Link"; - -const steps: { icon: LucideIcon; title: string; body: string; href: string }[] = - [ - { - icon: Server, - title: "Join a server", - body: "Runs on listed servers count here.", - href: "/servers", - }, - { - icon: Map, - title: "Pick a map", - body: "Leaderboards and record history for each.", - href: "/maps", - }, - { - icon: Activity, - title: "Follow the times", - body: "New runs and world records as they land.", - href: "/activity", - }, - ]; - -export function GetStarted() { - return ( -
-

- Your times, on one global list -

-
    - {steps.map(({ icon: Icon, ...step }) => ( -
  1. - - - - - - - {step.title} - {step.body} - - - - -
  2. - ))} -
-
- ); -} diff --git a/web/src/features/home/HomeHeader.tsx b/web/src/features/home/HomeHeader.tsx index d461f2b..7f6dd9f 100644 --- a/web/src/features/home/HomeHeader.tsx +++ b/web/src/features/home/HomeHeader.tsx @@ -21,7 +21,7 @@ const nativePlacement = { /** A static import, so Next.js knows the size, serves modern formats at the screen's width, and blurs in. */ export function HomeHeader() { return ( -
+
{/* On a phone the text takes the lower half, so the picture fills only the top two thirds and fades out there: the jumper then sits between the top edge and the text instead of behind it. The settle zoom is on this box so the depth canvas moves with the picture. */} @@ -47,7 +47,7 @@ export function HomeHeader() { any part of it. */}
-
+

SourceJump

diff --git a/web/src/features/home/LiveNow.tsx b/web/src/features/home/LiveNow.tsx index 0244998..d49b268 100644 --- a/web/src/features/home/LiveNow.tsx +++ b/web/src/features/home/LiveNow.tsx @@ -1,205 +1,372 @@ -// The home page's live part: the newest world records beside the busiest servers online right now. -import { ArrowRight } from "lucide-react"; -import type { CSSProperties } from "react"; +// The home page's live part, under its header: a strip of the numbers that say how busy SourceJump is (players on +// now, the latest day's runs, the week's world records), the newest world records beside the top of the points +// board, then the servers people are playing on now. +import type { CSSProperties, ReactNode } from "react"; import { api, type Schemas } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; import { RunLink } from "@/features/runs/RunLink"; -import { formatSince, formatTime, trackName } from "@/features/runs/time"; +import { ReplayLink } from "@/features/replays/ReplayLink"; +import { + formatAge, + formatDate, + formatTime, + trackName, +} from "@/features/runs/time"; +import { ServerRow } from "@/features/servers/ServerRow"; import { Avatar } from "@/ui/Avatar"; import { buttonClasses } from "@/ui/Button"; -import { Card, Label } from "@/ui/Card"; -import { DividedList } from "@/ui/Divided"; +import { classNames } from "@/ui/classNames"; +import { CountUp } from "@/ui/CountUp"; import { Flag } from "@/ui/Flag"; import { Link } from "@/ui/Link"; +import { Medal } from "@/ui/Medal"; +import { TierBadge } from "@/ui/TierBadge"; -const RECORDS = 6; +const RECORDS = 8; +const LEADERS = 10; const SERVERS = 4; +const numbers = new Intl.NumberFormat("en"); export async function LiveNow() { - const [records, servers, styles] = await Promise.all([ + // Each part shows what it has; one that can't be loaded says so, or (the strip) leaves its number out. + const [records, servers, leaders, runs, styles] = await Promise.all([ api .GET("/v1/runs", { params: { query: { records: true, limit: RECORDS } } }) .catch(() => undefined), api.GET("/v1/servers").catch(() => undefined), + api + .GET("/v1/leaderboards/{ranking}", { + params: { path: { ranking: "points" }, query: { limit: LEADERS } }, + }) + .catch(() => undefined), + api + .GET("/v1/daily-totals/runs", { params: { query: { range: "month" } } }) + .catch(() => undefined), currentStyles(), ]); + const listed = servers?.data?.servers; + // The API lists online servers first, busiest first. + const online = listed?.filter((server) => server.online) ?? []; + const lastDay = runs?.data?.points.at(-1); + const week = runs?.data?.points.slice(-7) ?? []; + const board = leaders?.data; + return ( -

- - - Latest world records - - {records?.data ? ( - 1 ? styles.name : undefined} - /> - ) : ( -

- Records couldn't be loaded. Try again in a moment. -

- )} -
- - - Online now - - {servers?.data ? ( - + <> + sum + server.players, 0), + live: true, + detail: `on ${online.length} of ${listed.length} servers`, + href: "/servers", + }, + lastDay && { + label: `Runs on ${formatDate(lastDay.day).replace(/, \d{4}$/, "")}`, + value: lastDay.runs, + detail: `${numbers.format(lastDay.world_records)} world ${lastDay.world_records === 1 ? "record" : "records"}`, + href: "/activity", + }, + week.length > 0 && { + label: "World records, last 7 days", + value: week.reduce((sum, day) => sum + day.world_records, 0), + detail: `from ${numbers.format(week.reduce((sum, day) => sum + day.runs, 0))} runs`, + href: "/activity?show=records", + }, + ]} + /> + +
+ + {records?.data ? ( + 1 ? styles.name : undefined} + /> + ) : ( + Records couldn't be loaded. Try again in a moment. + )} + + + {board ? ( + + ) : ( + + The leaderboard couldn't be loaded. Try again in a moment. + + )} + +
+ + + {!listed ? ( + Servers couldn't be loaded. Try again in a moment. + ) : online.length === 0 ? ( +
+

+ No servers are online right now. The server list shows where + players were last seen. +

+ + Server list + +
) : ( -

- Servers couldn't be loaded. Try again in a moment. -

+ // The Servers page's own rows, two to a line, with the lines between them drawn by each cell. +
    + {online.slice(0, SERVERS).map((server, index) => ( +
  • + +
  • + ))} +
)} -
+ + + ); +} + +interface PulseCell { + label: string; + value: number; + /** A count of what's happening right now, in the green of the servers' online dots. */ + live?: boolean; + detail: string; + href: string; +} + +/** The numbers that say how busy SourceJump is, each opening the page it comes from. */ +function Pulse({ + cells, +}: { + cells: (PulseCell | false | 0 | null | undefined)[]; +}) { + const shown = cells.filter((cell): cell is PulseCell => !!cell); + if (shown.length === 0) return null; + return ( +
+ {shown.map((cell) => ( + + {cell.label} + + + + + {cell.detail} + + + ))}
); } -function Heading({ +function Panel({ + title, href, link, + note, + className, children, }: { + title: string; href: string; link: string; - children: string; + /** Beside the title, e.g. which board the panel shows. */ + note?: ReactNode; + className?: string; + children: ReactNode; }) { return ( -
- - - {link} - - -
+
+
+

+ {title} + {note && ( + {note} + )} +

+ + {link} + +
+ {children} +
); } +function Note({ children }: { children: ReactNode }) { + return

{children}

; +} + function Records({ runs, + tierCount, styleName, }: { runs: Schemas["RecentRun"][]; + tierCount: number | null; /** Given when more than one style is ranked, so each record names its own. */ styleName?: (key: string) => string; }) { - if (runs.length === 0) { - return

No world records yet.

; - } + if (runs.length === 0) return No world records yet.; return ( - +
    {runs.map((run, index) => (
  • - - - + + {/* The map first, on its own line: on a records feed, where it was set is what reads at a glance. The + player, and the style and track, beneath. */} + + {run.tier != null && tierCount != null && ( + + )} 0 ? `&track=${run.track}` : ""}`} className="hover:text-accent truncate font-bold" > - {run.player.name} + {run.map} - - + + 0 ? `&track=${run.track}` : ""}`} - className="hover:text-accent" + href={`/players/${run.player.steamid64}`} + className="hover:text-accent truncate" > - {run.map} + {run.player.name} - {[run.track > 0 && trackName(run.track), styleName?.(run.style)] - .filter(Boolean) - .map((part) => ` · ${part}`)} - - - - {/* Every row is a world record, so the time says by how much it beat the last one instead of "WR". */} - - {run.gap != null && run.gap < 0 && ( - - −{formatTime(-run.gap)} + {/* Most players have no country on Steam; a placeholder on every row would only be noise. */} + {run.player.country_code && ( + + )} + {(run.track > 0 || styleName) && ( + + {[ + run.track > 0 && trackName(run.track), + styleName?.(run.style), + ] + .filter(Boolean) + .join(" · ")} )} + + + {/* As on the Activity board: the time with what it took off the old record in brackets, how long ago + beneath, then the replay. */} + + {formatTime(run.time)} + {run.gap != null && run.gap < 0 && ( + + (−{formatTime(-run.gap)}) + + )} - - {/* Counted from now, which differs between the server's render and the browser's. */} - - + {/* Counted from now, which differs between the server's render and the browser's. */} + +
  • ))} - +
); } -function Servers({ servers }: { servers: Schemas["ListedServer"][] }) { - // The API lists online servers first, busiest first. - const online = servers.filter((server) => server.online).slice(0, SERVERS); - if (online.length === 0) { - return ( -
-

- No servers are online right now. The server list shows where players - were last seen. -

- - Server list - -
- ); - } +function Leaders({ standings }: { standings: Schemas["Standing"][] }) { + if (standings.length === 0) return No one has points yet.; return ( - - {online.map((server) => { - const address = `${server.ip}:${server.port}`; - return ( -
  • - - {server.hostname} - - {server.map} - +
      + {standings.map((standing, index) => ( +
    1. + + + + + {standing.player.name} - - - - {server.players} - /{server.max_slots} + {standing.player.country_code && ( + + )} + + + {numbers.format(standing.points)} + + + {standing.completed} {standing.completed === 1 ? "map" : "maps"} - - Join - -
    2. - ); - })} - + + + ))} +
    ); } diff --git a/web/src/features/home/strafeSim.test.ts b/web/src/features/home/strafeSim.test.ts deleted file mode 100644 index 1f71202..0000000 --- a/web/src/features/home/strafeSim.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { simulateStrafes, tickSeconds } from "./strafeSim"; - -describe("simulateStrafes", () => { - const ticks = simulateStrafes(10); - - it("gains speed from strafing alone", () => { - expect(ticks[0]!.speed).toBeGreaterThanOrEqual(250); - expect(ticks.at(-1)!.speed).toBeGreaterThan(600); - // Only switching strafes costs speed, a little, on the tick the keys change; every other tick gains. - for (let i = 1; i < ticks.length; i++) { - const change = ticks[i]!.speed - ticks[i - 1]!.speed; - if (ticks[i]!.jump) expect(change).toBeGreaterThan(-1); - else expect(change).toBeGreaterThan(0); - } - }); - - it("jumps on landing, once per Source jump arc", () => { - const jumps = ticks.flatMap((tick, index) => (tick.jump ? [index] : [])); - // A jump at 57 units of height lasts about 0.755 s under 800 gravity. - const gaps = jumps.slice(1).map((jump, i) => jump - jumps[i]!); - for (const gap of gaps) { - expect(gap * tickSeconds).toBeCloseTo(0.755, 1); - } - for (const index of jumps.slice(1)) { - expect(ticks[index - 1]!.z).toBeLessThan(5); - } - }); - - it("switches strafe key with each hop and weaves around the line forward", () => { - const keys = ticks.filter((tick) => tick.jump).map((tick) => tick.key); - keys.slice(1).forEach((key, i) => expect(key).not.toBe(keys[i])); - const ys = ticks.map((tick) => tick.y); - expect(Math.min(...ys)).toBeLessThan(-30); - expect(Math.max(...ys)).toBeGreaterThan(30); - }); -}); diff --git a/web/src/features/home/strafeSim.ts b/web/src/features/home/strafeSim.ts deleted file mode 100644 index 363a562..0000000 --- a/web/src/features/home/strafeSim.ts +++ /dev/null @@ -1,93 +0,0 @@ -// The home page's bhop demo, simulated: a player chaining hops and strafing, moved by Source's air rules. - -// Source's movement constants as CS:S ships them. The air acceleration and the turn rate aren't any server's -// setting or a real player's input; they're picked so the demo's path weaves visibly at a readable pace. -const TICK = 1 / 100; -const GRAVITY = 800; -const JUMP_SPEED = Math.sqrt(2 * GRAVITY * 57); -const MAX_SPEED = 250; -const AIR_WISH_CAP = 30; -const AIR_ACCELERATE = 100; -const TURN_RATE = (100 * Math.PI) / 180; - -/** One tick of the demo, in Source units (x forward, y left, z up) and seconds. */ -export interface StrafeTick { - x: number; - y: number; - z: number; - /** Horizontal speed, the number a speedometer shows. */ - speed: number; - /** Where the player looks, in radians. */ - yaw: number; - /** The strafe key held: A turns left, D right. */ - key: "A" | "D"; - /** True on the tick the player lands and jumps again. */ - jump: boolean; -} - -/** - * Runs `seconds` of perfect hops from running speed. Each hop is one strafe: the player holds A and turns the - * mouse left, lands, jumps on the same tick, then holds D and turns right. Speed is never set, only gained: - * it comes out of Source's air acceleration (PM_AirAccelerate), the same rule the game runs. - */ -export function simulateStrafes(seconds: number): StrafeTick[] { - const ticks: StrafeTick[] = []; - // Facing a quarter turn right of the way forward, so the alternating strafes weave around the x axis. - let yaw = -TURN_RATE * airTime() * 0.5; - let vx = MAX_SPEED * Math.cos(yaw); - let vy = MAX_SPEED * Math.sin(yaw); - let vz = JUMP_SPEED; - let x = 0; - let y = 0; - let z = 0; - let left = true; - - for (let tick = 0; tick * TICK < seconds; tick++) { - let jump = tick === 0; - if (z <= 0 && vz < 0) { - // Jumping on the landing tick skips ground friction, so no speed is lost between hops. - z = 0; - vz = JUMP_SPEED; - left = !left; - jump = true; - } - - yaw += (left ? 1 : -1) * TURN_RATE * TICK; - // A or D alone: the wanted direction is square to the view, to the side being turned towards. - const wishX = Math.cos(yaw + (left ? 1 : -1) * (Math.PI / 2)); - const wishY = Math.sin(yaw + (left ? 1 : -1) * (Math.PI / 2)); - // The air cap is what makes strafing work: only speed along the wanted direction is limited, so steering - // keeps that projection low and every tick adds a little speed sideways. - const current = vx * wishX + vy * wishY; - const add = Math.min( - AIR_WISH_CAP - current, - AIR_ACCELERATE * MAX_SPEED * TICK, - ); - if (add > 0) { - vx += add * wishX; - vy += add * wishY; - } - - vz -= GRAVITY * TICK; - x += vx * TICK; - y += vy * TICK; - z = Math.max(z + vz * TICK, 0); - ticks.push({ - x, - y, - z, - speed: Math.hypot(vx, vy), - yaw, - key: left ? "A" : "D", - jump, - }); - } - return ticks; -} - -function airTime(): number { - return (2 * JUMP_SPEED) / GRAVITY; -} - -/** How long one tick lasts, for playing the ticks back in real time. */ -export const tickSeconds = TICK; diff --git a/web/src/features/leaderboards/BoardChoices.tsx b/web/src/features/leaderboards/BoardChoices.tsx index b794fe7..05861a8 100644 --- a/web/src/features/leaderboards/BoardChoices.tsx +++ b/web/src/features/leaderboards/BoardChoices.tsx @@ -9,6 +9,12 @@ import { LinkTabs } from "@/ui/LinkTabs"; export type Track = Schemas["LeaderboardTrack"]; /** Players per page of a full list. */ export const LIST_PAGE_SIZE = 50; +/** + * Players per page of each list on the overview, and per request: five pages, turned in the browser. Here and + * not in StandingsPanel, a client module, whose exports reach server code only as references. + */ +export const OVERVIEW_PAGE_SIZE = 20; +export const OVERVIEW_CHUNK = 100; type Styles = Awaited>; export interface BoardParams { diff --git a/web/src/features/leaderboards/LeaderboardList.tsx b/web/src/features/leaderboards/LeaderboardList.tsx index b650e37..94cc2a8 100644 --- a/web/src/features/leaderboards/LeaderboardList.tsx +++ b/web/src/features/leaderboards/LeaderboardList.tsx @@ -1,4 +1,5 @@ -// One leaderboard in full, by points or by completions, under the same choices as the overview it opens from. +// One leaderboard in full, by points or by completions, a page at a time, under the same choices as the overview +// it opens from. import { ArrowLeft } from "lucide-react"; import { api } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; @@ -27,17 +28,25 @@ export function listTitle(ranking: Ranking, track: string | undefined) { export async function LeaderboardList({ ranking, params, + page: requested, }: { ranking: Ranking; params: BoardParams; + /** `?page=` as given. */ + page?: string; }) { + const page = Math.max(1, Math.floor(Number(requested)) || 1); const styles = await currentStyles(); const board = boardFrom(params, styles); const list = await api .GET("/v1/leaderboards/{ranking}", { params: { path: { ranking }, - query: { ...boardApiQuery(board), limit: LIST_PAGE_SIZE }, + query: { + ...boardApiQuery(board), + limit: LIST_PAGE_SIZE, + offset: (page - 1) * LIST_PAGE_SIZE, + }, }, }) .then((result) => result.data) @@ -68,14 +77,27 @@ export async function LeaderboardList({

    This leaderboard couldn't be loaded. Try again in a moment.

    ) : list.standings.length === 0 ? ( - {ranking === "points" - ? !board.legacy && !list.points.tiers - ? "Points start once maps have tiers." - : "Nobody has points here yet." - : "Nobody has finished one yet."} + {page > 1 + ? "There's no page this far." + : ranking === "points" + ? !board.legacy && !list.points.tiers + ? "Points start once maps have tiers." + : "Nobody has points here yet." + : "Nobody has finished one yet."} ) : ( - + { + const search = new URLSearchParams(query); + if (to > 1) search.set("page", String(to)); + const text = search.toString(); + return `/leaderboards/${ranking}${text ? `?${text}` : ""}`; + }} + completedLabel={label} + /> )} {list && ranking === "points" && ( diff --git a/web/src/features/leaderboards/Leaderboards.tsx b/web/src/features/leaderboards/Leaderboards.tsx index f3a502f..de24b98 100644 --- a/web/src/features/leaderboards/Leaderboards.tsx +++ b/web/src/features/leaderboards/Leaderboards.tsx @@ -1,144 +1,106 @@ // The Leaderboards page: in one style and kind of track, the top players by points and by completions, side -// by side. Pre-2.0 switches both lists to the old site's records. -import { ArrowRight } from "lucide-react"; -import type { CSSProperties, ReactNode } from "react"; +// by side, each a page at a time with its own pager, turning without a wait (StandingsPanel). Pre-2.0 switches +// both lists to the old site's records. import { api, type Schemas } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; -import { Avatar } from "@/ui/Avatar"; -import { Card } from "@/ui/Card"; -import { Flag } from "@/ui/Flag"; -import { Link } from "@/ui/Link"; -import { Medal } from "@/ui/Medal"; import { + type Board, type BoardParams, BoardChoices, boardApiQuery, boardFrom, boardQuery, completedLabel, + OVERVIEW_CHUNK as CHUNK, + OVERVIEW_PAGE_SIZE as PAGE_SIZE, } from "./BoardChoices"; import { PointsNote } from "./PointsNote"; +import { StandingsPanel } from "./StandingsPanel"; -type Standing = Schemas["Standing"]; +type Ranking = Schemas["Ranking"]; + +/** Each list keeps its own page in the address, so paging one leaves the other where it is. */ +const PAGE_PARAM: Record = { + points: "points_page", + completed: "completed_page", +}; const numbers = new Intl.NumberFormat("en"); -const percent = new Intl.NumberFormat("en", { style: "percent" }); -export async function Leaderboards({ params }: { params: BoardParams }) { +export async function Leaderboards({ + params, + pages, +}: { + params: BoardParams; + /** The `points_page` and `completed_page` from the address, as given. */ + pages: Partial>; +}) { const styles = await currentStyles(); const choice = boardFrom(params, styles); - const legacy = choice.legacy; - const board = await api - .GET("/v1/leaderboards", { params: { query: boardApiQuery(choice) } }) - .then((result) => result.data) - .catch(() => undefined); const query = boardQuery(choice, styles); + const chunkOf = (ranking: Ranking) => { + const page = Math.max(1, Math.floor(Number(pages[ranking])) || 1); + return Math.floor(((page - 1) * PAGE_SIZE) / CHUNK); + }; + const [points, completed] = await Promise.all([ + load("points", choice, chunkOf("points")), + load("completed", choice, chunkOf("completed")), + ]); + const formula = points?.points ?? completed?.points; + const apiQuery = boardApiQuery(choice); return ( -
    +
    - - {!board ? ( -

    The leaderboards couldn't be loaded. Try again in a moment.

    - ) : ( - <> - {/* Keyed by what's shown, so every row enters on a new choice, not only the players who are new. */} -
    - numbers.format(standing.points)} - /> - ( - <> - {numbers.format(standing.completed)} - {board.out_of > 0 && ( - - {percent.format(standing.completed / board.out_of)} - - )} - - )} - /> -
    - - - )} + {/* Keyed by the board, so another choice starts both lists again from what the server sent. */} +
    + + +
    + {formula && }
    ); } -function List({ - title, - more, - standings, - empty, - value, -}: { - title: string; - /** The full list's page. */ - more: string; - standings: Standing[]; - empty: string; - value: (standing: Standing) => ReactNode; -}) { - return ( - -

    {title}

    - {standings.length === 0 ? ( -

    {empty}

    - ) : ( -
      - {standings.map((standing, index) => ( -
    1. - - - - {standing.player.name} - - - - {value(standing)} - -
    2. - ))} -
    - )} - {standings.length > 0 && ( - - Show more - - - )} -
    - ); +/** The hundred players around the page asked for; undefined when they can't be loaded. */ +function load(ranking: Ranking, board: Board, chunk: number) { + return api + .GET("/v1/leaderboards/{ranking}", { + params: { + path: { ranking }, + query: { ...boardApiQuery(board), limit: CHUNK, offset: chunk * CHUNK }, + }, + }) + .then((result) => result.data) + .catch(() => undefined); } diff --git a/web/src/features/leaderboards/StandingsPanel.tsx b/web/src/features/leaderboards/StandingsPanel.tsx new file mode 100644 index 0000000..a07dba2 --- /dev/null +++ b/web/src/features/leaderboards/StandingsPanel.tsx @@ -0,0 +1,289 @@ +"use client"; +// One list of the Leaderboards page, a page of 20 at a time, turning without a wait as on the Activity board: +// the server sends the hundred players around the page asked for, pages within them turn here at once, and the +// hundreds either side load ahead, so Next and Previous never wait. The pager's links still work without script. +import { useSearchParams } from "next/navigation"; +import { + type CSSProperties, + type FormEvent, + type MouseEvent, + type ReactNode, + useCallback, + useEffect, + useRef, + useState, +} from "react"; +import { api, type Schemas } from "@/api/client"; +import { Avatar } from "@/ui/Avatar"; +import { Flag } from "@/ui/Flag"; +import { Link } from "@/ui/Link"; +import { Medal } from "@/ui/Medal"; +import { Pager } from "@/ui/Pager"; +import { OVERVIEW_CHUNK, OVERVIEW_PAGE_SIZE } from "./BoardChoices"; + +type Standing = Schemas["ListedStanding"]; +type Ranking = Schemas["Ranking"]; + +const PAGE_SIZE = OVERVIEW_PAGE_SIZE; +const CHUNK = OVERVIEW_CHUNK; + +const numbers = new Intl.NumberFormat("en"); +const percent = new Intl.NumberFormat("en", { style: "percent" }); + +export function StandingsPanel({ + ranking, + title, + note, + full, + param, + apiQuery, + first, + firstChunk, + total, + outOf, + bonuses, + empty, +}: { + ranking: Ranking; + title: string; + /** Beside the title, e.g. that points are a draft. */ + note?: string; + /** The list on its own page, with more columns. */ + full: string; + /** This list's page in the address. */ + param: string; + /** What the API takes for this board, without the paging. */ + apiQuery: Record; + /** The chunk the page asked for falls in, from the server; undefined when it couldn't be loaded. */ + first: Standing[] | undefined; + firstChunk: number; + total: number; + /** What completions are counted out of. */ + outOf: number; + bonuses: boolean; + empty: string; +}) { + const params = useSearchParams(); + const asked = Math.max(1, Math.floor(Number(params.get(param))) || 1); + const [chunks, setChunks] = useState>( + first ? { [firstChunk]: first } : {}, + ); + const [failed, setFailed] = useState(false); + /** Set after the first turn: pages turned here appear at once, without the rows' entrance. */ + const [turned, setTurned] = useState(false); + const inFlight = useRef(new Map>()); + /** The chunks loaded so far, read by `load` without waiting for a render. */ + const loaded = useRef(chunks); + + const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE)); + const page = Math.min(asked, pageCount); + const chunkOf = (p: number) => Math.floor(((p - 1) * PAGE_SIZE) / CHUNK); + + const load = useCallback( + (k: number): Promise => { + if (loaded.current[k]) return Promise.resolve(true); + const pending = inFlight.current.get(k); + if (pending) return pending; + const request = api + .GET("/v1/leaderboards/{ranking}", { + params: { + path: { ranking }, + query: { ...apiQuery, limit: CHUNK, offset: k * CHUNK }, + }, + }) + .then((result) => result.data) + .catch(() => undefined) + .then((list) => { + inFlight.current.delete(k); + if (!list) { + setFailed(true); + return false; + } + setFailed(false); + loaded.current = { ...loaded.current, [k]: list.standings }; + setChunks(loaded.current); + return true; + }); + inFlight.current.set(k, request); + return request; + }, + [ranking, apiQuery], + ); + + // The page shown, and the hundreds either side of it, ready before they're asked for. + const shownChunk = chunkOf(page); + useEffect(() => { + void load(shownChunk).then((ok) => { + if (!ok) return; + if ((shownChunk + 1) * CHUNK < total) void load(shownChunk + 1); + if (shownChunk > 0) void load(shownChunk - 1); + }); + }, [shownChunk, total, load]); + + /** This list's page in the address, keeping the board and the other list's page. */ + const pageHref = useCallback( + (to: number) => { + const search = new URLSearchParams(params.toString()); + if (to > 1) search.set(param, String(to)); + else search.delete(param); + const text = search.toString(); + return text ? `/leaderboards?${text}` : "/leaderboards"; + }, + [params, param], + ); + + const turns = useRef(0); + async function go(target: number) { + const turn = ++turns.current; + const wanted = Math.min(Math.max(1, target), pageCount); + if (!(await load(chunkOf(wanted))) || turn !== turns.current) return; + setTurned(true); + window.history.pushState(null, "", pageHref(wanted)); + } + + function onPagerClick(event: MouseEvent) { + const link = (event.target as HTMLElement).closest("a"); + if ( + !link || + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) + return; + // Stopped here too, as Next's Link navigates even when the event is already prevented. + event.preventDefault(); + event.stopPropagation(); + void go(Number(new URL(link.href).searchParams.get(param) ?? 1)); + } + + function onPagerSubmit(event: FormEvent) { + event.preventDefault(); + event.stopPropagation(); + const form = event.target as HTMLFormElement; + const typed = Math.floor(Number(new FormData(form).get(param))); + form.reset(); + if (typed >= 1) void go(typed); + } + + const chunk = chunks[shownChunk]; + const start = (page - 1) * PAGE_SIZE - shownChunk * CHUNK; + const shown = chunk?.slice(start, start + PAGE_SIZE); + + return ( +
    +
    +

    + {title} + {note && ( + {note} + )} +

    + + Full table + +
    + {total === 0 && first ? ( +

    {empty}

    + ) : !shown ? ( +

    + {failed + ? "This list couldn't be loaded. Try again in a moment." + : "Loading…"} +

    + ) : ( +
      + {shown.map((standing, index) => ( +
    1. + + {ranking === "points" ? ( + <> + + {numbers.format(standing.points)} + + + {numbers.format(standing.completed)}{" "} + {bonuses ? "bonuses" : "maps"} + + + ) : ( + <> + + {numbers.format(standing.completed)} + + {outOf > 0 && ( + + {percent.format(standing.completed / outOf)} + + )} + + )} + +
    2. + ))} +
    + )} + {total > PAGE_SIZE && ( +
    + +
    + )} +
    + ); +} + +function Row({ + standing, + children, +}: { + standing: Standing; + children: ReactNode; +}) { + return ( + + + + + {standing.player.name} + + {/* Most players have no country on Steam; a placeholder on every row would only be noise. */} + {standing.player.country_code && ( + + )} + + {children} + + + ); +} diff --git a/web/src/features/leaderboards/StandingsTable.tsx b/web/src/features/leaderboards/StandingsTable.tsx index 8b6a083..fbdefcb 100644 --- a/web/src/features/leaderboards/StandingsTable.tsx +++ b/web/src/features/leaderboards/StandingsTable.tsx @@ -1,13 +1,12 @@ -"use client"; -// One leaderboard in full, as a table: the first 50 come with the page and "Show more" loads 50 at a time. -// Beside each player's points and completions, their share of the tracks and their world records. -import { type CSSProperties, useState } from "react"; -import { api, type Schemas } from "@/api/client"; +// One leaderboard in full, as a table, a page of 50 at a time with page links beneath. Beside each player's points +// and completions, their share of the tracks and their world records. +import type { CSSProperties } from "react"; +import type { Schemas } from "@/api/client"; import { Avatar } from "@/ui/Avatar"; -import { Button } from "@/ui/Button"; import { Flag } from "@/ui/Flag"; import { Link } from "@/ui/Link"; import { Medal } from "@/ui/Medal"; +import { Pager } from "@/ui/Pager"; import { Table, TableBody, @@ -23,67 +22,24 @@ const percent = new Intl.NumberFormat("en", { style: "percent" }); type List = Schemas["LeaderboardList"]; -/** Give it a `key` per board, so another choice starts again from the top. */ export function StandingsTable({ - first, + list, + page, + href, completedLabel, }: { - first: List; + list: List; + page: number; + /** The address of another page of this board. */ + href: (page: number) => string; /** "Completed maps" or "Completed bonuses". */ completedLabel: string; }) { - const [standings, setStandings] = useState(first.standings); - // Rows read so far, counting repeats, so a page of players already shown still moves the next one on. - const [offset, setOffset] = useState(first.standings.length); - const [loading, setLoading] = useState(false); - const [failed, setFailed] = useState(false); - // Set when a page comes back empty: players left the board since the first page, so the total overstates it. - const [ended, setEnded] = useState(false); - const complete = ended || standings.length >= first.total; + const first = list; + const standings = list.standings; const byPoints = first.ranking === "points"; const legacy = first.view === "legacy"; - async function showMore() { - setLoading(true); - setFailed(false); - const loaded = await api - .GET("/v1/leaderboards/{ranking}", { - params: { - path: { ranking: first.ranking }, - query: { - ...(legacy - ? { view: "legacy" } - : { - style: first.style ?? undefined, - track: first.track, - view: "current", - }), - limit: PAGE_SIZE, - offset, - }, - }, - }) - .then((result) => result.data) - .catch(() => undefined); - setLoading(false); - if (!loaded) { - setFailed(true); - return; - } - if (loaded.standings.length === 0) setEnded(true); - setOffset((read) => read + loaded.standings.length); - // Standings move while someone reads them, so a player already shown can come again on a later page. - setStandings((shown) => { - const seen = new Set(shown.map((standing) => standing.player.steamid64)); - return [ - ...shown, - ...loaded.standings.filter( - (standing) => !seen.has(standing.player.steamid64), - ), - ]; - }); - } - // The ranked value comes first after the player, the other one after it. const pointsCell = (standing: Schemas["ListedStanding"]) => ( @@ -130,10 +86,9 @@ export function StandingsTable({ @@ -153,7 +108,9 @@ export function StandingsTable({ /> {standing.player.name} - + {standing.player.country_code && ( + + )} {byPoints ? ( @@ -176,23 +133,13 @@ export function StandingsTable({ ))} -
    - - {complete - ? `All ${numbers.format(ended ? standings.length : first.total)} players` - : `Top ${numbers.format(standings.length)} of ${numbers.format(first.total)} players`} - - {failed && ( - - More couldn't be loaded. Try again. - - )} - {!complete && ( - - )} -
    +
    ); } diff --git a/web/src/features/maps/MapList.tsx b/web/src/features/maps/MapList.tsx index b96b753..02a2627 100644 --- a/web/src/features/maps/MapList.tsx +++ b/web/src/features/maps/MapList.tsx @@ -1,7 +1,7 @@ // The Maps page's totals (maps, tiered maps, maps per tier), its search, sort, style and completion choices, // and one row per map with its picture, tier and world record. Staff who manage maps also get a "No runs yet" tab // and a "Map files" tab for uploading viewer files in bulk, and can set up a map by name before its first run. -import { Search, X } from "lucide-react"; +import { X } from "lucide-react"; import Form from "next/form"; import type { CSSProperties } from "react"; import { api, type Schemas } from "@/api/client"; @@ -12,10 +12,10 @@ import { formatSince, formatTime } from "@/features/runs/time"; import { BulkUpload } from "@/features/staff/maps/BulkUpload"; import { UnplayedMaps } from "@/features/staff/maps/UnplayedMaps"; import { Avatar } from "@/ui/Avatar"; -import { Button, ButtonLink } from "@/ui/Button"; +import { ButtonLink } from "@/ui/Button"; import { Card } from "@/ui/Card"; import { Flag } from "@/ui/Flag"; -import { Input } from "@/ui/Input"; +import { SearchField } from "@/ui/SearchField"; import { Link } from "@/ui/Link"; import { ChoiceBar } from "@/ui/ChoiceBar"; import { ChoiceMenu } from "@/ui/ChoiceMenu"; @@ -213,7 +213,7 @@ export async function MapList({ params }: { params: MapListParams }) { newestHref={href({ sort: "newest", tier: null, page: 1 })} /> )} -
    + {/* Searching keeps the chosen tab, sort, style and completion filter. */} {unplayed && } {completion !== "all" && filterPlayer && ( @@ -229,16 +229,12 @@ export async function MapList({ params }: { params: MapListParams }) { )} {tier != null && } - -
    diff --git a/web/src/features/players/PlayerDetails.tsx b/web/src/features/players/PlayerDetails.tsx index 3a85416..667c113 100644 --- a/web/src/features/players/PlayerDetails.tsx +++ b/web/src/features/players/PlayerDetails.tsx @@ -1,5 +1,5 @@ // The top of a player's profile: their setup as they describe it (mouse, DPI, sensitivity and so on), with a -// way to change it for the player themself and for staff who manage bans. A line sets it apart from runs. +// way to change it for the player themself and for staff who manage bans. import { api, type Schemas } from "@/api/client"; import type { signedInPlayer } from "@/features/auth/signedInPlayer"; import { detailFields } from "./detailFields"; @@ -23,9 +23,13 @@ export async function PlayerDetails({
    {shown.length > 0 ? ( -
    + // One row of specs on wider screens, ruled apart like a spec sheet; a two-column grid on a phone. +
    {shown.map(({ key, label }) => ( -
    +
    {label}
    @@ -56,7 +60,6 @@ export async function PlayerDetails({ From the old site{own ? ", until you save your own" : ""}.

    )} -
    ); } diff --git a/web/src/features/players/PlayerFinder.tsx b/web/src/features/players/PlayerFinder.tsx new file mode 100644 index 0000000..6cebb8f --- /dev/null +++ b/web/src/features/players/PlayerFinder.tsx @@ -0,0 +1,215 @@ +"use client"; +// The Players page's search, answering as you type: the field beside the title, and in the panel under it the +// players matching what's typed, or with nothing typed, what the server sent (recently active players, or for +// staff the banned ones). Searches run in the browser the way the header's does: a short pause, each keystroke +// cancelling the request still out, late replies dropped, results kept up until the next arrive, and answers +// cached. The address follows, so a search can be shared; without script the form still submits. +import { Search, X } from "lucide-react"; +import Form from "next/form"; +import { type ReactNode, useEffect, useRef, useState } from "react"; +import { api, type Schemas } from "@/api/client"; +import { ButtonLink } from "@/ui/Button"; +import { PlayerRows, SEARCH_LIMIT } from "./PlayerRows"; +import { STEAMID } from "./steamId"; + +const PAUSE_MS = 150; + +type Players = Schemas["PlayerSummary"][]; + +export function PlayerFinder({ + heading, + initialQuery, + initialPlayers, + initialNow, + defaultTitle, + defaultAside, + children, + canManage, +}: { + /** The page's title and count, on the field's line. */ + heading: ReactNode; + initialQuery: string; + /** The server's answer for `initialQuery`; undefined when it couldn't be loaded. */ + initialPlayers: Players | undefined; + /** When the server asked, for the rows' "ago": time is read where data arrives, never while rendering. */ + initialNow: string; + /** The panel's title with nothing typed: "Recently active" or "Banned". */ + defaultTitle: ReactNode; + /** Beside it: what the times mean, or staff's tabs. */ + defaultAside: ReactNode; + /** The panel's body with nothing typed, rendered on the server. */ + children: ReactNode; + /** Staff who act on players, offered a SteamID nobody has seen. */ + canManage: boolean; +}) { + const [text, setText] = useState(initialQuery); + const [query, setQuery] = useState(initialQuery.trim()); + const [results, setResults] = useState<{ + query: string; + players: Players | undefined; + at: Date; + }>({ + query: initialQuery.trim(), + players: initialPlayers, + at: new Date(initialNow), + }); + const timer = useRef(undefined); + const controller = useRef(null); + const sequence = useRef(0); + const kept = useRef( + new Map( + initialPlayers + ? [[initialQuery.trim().toLowerCase(), initialPlayers]] + : [], + ), + ); + + useEffect( + () => () => { + window.clearTimeout(timer.current); + controller.current?.abort(); + }, + [], + ); + + function search(value: string) { + const next = value.trim(); + setQuery(next); + window.clearTimeout(timer.current); + controller.current?.abort(); + const seq = ++sequence.current; + // The address follows the field, replaced rather than pushed: one entry in the history per visit. + const url = new URL(window.location.href); + if (next) url.searchParams.set("q", next); + else url.searchParams.delete("q"); + window.history.replaceState(null, "", url); + if (!next) return; + const known = kept.current.get(next.toLowerCase()); + if (known) { + setResults({ query: next, players: known, at: new Date() }); + return; + } + timer.current = window.setTimeout(async () => { + const abort = new AbortController(); + controller.current = abort; + try { + const result = await api.GET("/v1/players", { + params: { query: { q: next, limit: SEARCH_LIMIT } }, + signal: abort.signal, + }); + if (seq !== sequence.current) return; + const players = result.data?.players; + if (players) kept.current.set(next.toLowerCase(), players); + setResults({ query: next, players, at: new Date() }); + } catch (error) { + if ((error as Error).name === "AbortError") return; + if (seq === sequence.current) + setResults({ query: next, players: undefined, at: new Date() }); + } + }, PAUSE_MS); + } + + const searching = query !== ""; + // What's shown stays until the answer for the current text arrives, so typing never blanks the panel. + const shown = results.players; + const pending = searching && results.query !== query; + + return ( + <> +
    + {heading} +
    event.preventDefault()} + > +
    + + { + setText(event.target.value); + search(event.target.value); + }} + className="border-border bg-surface text-text placeholder:text-text-subtle hover:border-border-strong focus:border-accent focus:bg-bg h-10 w-full rounded-lg border pr-10 pl-10 transition-colors duration-(--duration-fast) outline-none" + /> + {text && ( + + )} +
    +
    +
    + +
    +
    +

    + {!searching + ? defaultTitle + : shown && shown.length > 0 + ? shown.length === SEARCH_LIMIT + ? `First ${SEARCH_LIMIT} players matching “${results.query}”` + : `${shown.length === 1 ? "1 player matches" : `${shown.length} players match`} “${results.query}”` + : `Players matching “${query}”`} +

    + {!searching ? ( + defaultAside + ) : ( +

    + {shown?.length === SEARCH_LIMIT + ? "There may be more: add more of the name, or a SteamID." + : "Latest finished run"} +

    + )} +
    + {!searching ? ( + children + ) : !shown ? ( +

    + {pending + ? "Searching…" + : "That search didn't work. Try again in a moment."} +

    + ) : shown.length === 0 ? ( +
    + {pending ? "Searching…" : "No player has that name or SteamID."} + {!pending && canManage && STEAMID.test(query) && ( + + Manage {query} anyway + + )} +
    + ) : ( + + )} +
    + + ); +} diff --git a/web/src/features/players/PlayerHeader.tsx b/web/src/features/players/PlayerHeader.tsx index c2e6a54..ae54527 100644 --- a/web/src/features/players/PlayerHeader.tsx +++ b/web/src/features/players/PlayerHeader.tsx @@ -1,14 +1,20 @@ -// The top of a player's pages: avatar, name, flag and Steam profile link, with the Profile / Manage switch for -// staff. It sits in the player's layout, so switching to the Manage view keeps it in place. +// The top of a player's pages, a masthead across the page: avatar, name, flag, country, first and latest run +// and Steam profile link, with the Profile / Manage switch for staff. Behind it, a picture of the map of one of +// their best runs, named in the corner. It sits in the player's layout, so switching to the Manage view keeps it. import { ExternalLink } from "lucide-react"; import { notFound } from "next/navigation"; -import type { Schemas } from "@/api/client"; +import { api, type Schemas } from "@/api/client"; import { signedInPlayer } from "@/features/auth/signedInPlayer"; import { getStaffPlayer } from "@/features/staff/players/staffPlayer"; import { Avatar } from "@/ui/Avatar"; import { Badge } from "@/ui/Badge"; import { Flag } from "@/ui/Flag"; import { PathTabs } from "@/ui/PathTabs"; +import { formatDate, formatSince, formatTime } from "@/features/runs/time"; +import { Link } from "@/ui/Link"; +import { Masthead, type MastheadImage } from "@/ui/Masthead"; +import { Medal } from "@/ui/Medal"; +import { currentStyles } from "@/features/ruleset/styles"; import { getPlayer } from "./playerDetail"; export async function PlayerHeader({ steamid }: { steamid: string }) { @@ -31,52 +37,151 @@ export async function PlayerHeader({ steamid }: { steamid: string }) { const isOwn = me?.steamid64 === player.steamid64; const banned = staffView?.bans?.some((ban) => ban.active) ?? false; + // Country, first and latest run come with the public profile; a player only staff can see has none of them. + const country = player.country_code + ? countryNames.of(player.country_code) + : undefined; + const firstRun = profile?.first_run_at; + const lastRun = profile?.last_run_at; + const featured = profile && featuredRun(profile); + const [image, styles] = featured + ? await Promise.all([mapCover(featured.map), currentStyles()]) + : []; + return ( -
    - -
    -
    -

    {player.name}

    - - {banned && Banned} -
    - - Steam profile - - -
    - {/* A player SourceJump hasn't seen has no profile to switch to. */} - {manager && profile && ( - +
    + - )} -
    +
    + {/* One line of text, so the flag sits at the middle of the name's letters (`vertical-align: middle`) + rather than the middle of its line box, which reads as high beside a lowercase name. */} +
    +

    {player.name}

    + + {banned && ( + + Banned + + )} +
    + {/* Facts about the player, then the way out to Steam. The run dates count 2.0 runs alone. */} +
    +
    + {country && ( +
    +
    Country
    +
    {country}
    +
    + )} + {firstRun && ( +
    +
    First 2.0 run
    +
    + +
    +
    + )} + {lastRun && ( +
    +
    Latest run
    +
    + +
    +
    + )} +
    + + Steam profile + + +
    +
    + {/* A player SourceJump hasn't seen has no profile to switch to. */} + {manager && profile && ( + + )} + {/* What the picture is: the map, and the run on it. */} + {image && featured && ( +

    + + + {featured.map} + + {/* It may be any style's run, so the style is named. */} + {styles?.name(featured.style)} + {formatTime(featured.time)} +

    + )} +
    + ); } +/** + * The run whose map stands behind the header: the best placed of the personal bests that came with the profile + * (each style's first page of main tracks, by map), the latest of equals. Not necessarily their best overall. + */ +function featuredRun( + profile: Schemas["PlayerProfile"], +): (Schemas["PersonalBest"] & { rank: number }) | undefined { + let best: (Schemas["PersonalBest"] & { rank: number }) | undefined; + for (const pb of profile.styles.flatMap((style) => style.personal_bests)) { + if (pb.rank == null || pb.legacy) continue; + if ( + !best || + pb.rank < best.rank || + (pb.rank === best.rank && + (pb.finished_at ?? "") > (best.finished_at ?? "")) + ) { + best = { ...pb, rank: pb.rank }; + } + } + return best; +} + +/** A map's cover picture; none when it has no pictures or can't be loaded, and the header goes without. */ +async function mapCover(map: string): Promise { + const result = await api + .GET("/v1/maps/{map}", { params: { path: { map } } }) + .catch(() => undefined); + const cover = result?.data?.images[0]; + return cover + ? { url: cover.url, thumbnailUrl: cover.thumbnail_url, focus: cover.focus } + : undefined; +} + +const countryNames = new Intl.DisplayNames(["en"], { type: "region" }); + /** Who sees the Manage view: staff who can act on players. The API checks each privilege again. */ export function managesPlayers( privileges: readonly Schemas["Privilege"][] | undefined, diff --git a/web/src/features/players/PlayerRows.tsx b/web/src/features/players/PlayerRows.tsx new file mode 100644 index 0000000..d886527 --- /dev/null +++ b/web/src/features/players/PlayerRows.tsx @@ -0,0 +1,86 @@ +// A list of players as the Players page shows them: two columns on wider screens, reading down each, a line +// between rows and between the columns. Each row is the player, their flag if they have one, and how long ago +// they last finished a run, in the accent within the hour. Rendered on the server for the first view and in +// the browser for searches as they're typed, so it holds no state of its own. +import type { CSSProperties } from "react"; +import type { Schemas } from "@/api/client"; +import { formatDate, formatSince } from "@/features/runs/time"; +import { Avatar } from "@/ui/Avatar"; +import { classNames } from "@/ui/classNames"; +import { Flag } from "@/ui/Flag"; +import { Link } from "@/ui/Link"; + +/** + * Players asked for per search, so a full answer can say there may be more. Here, in a module both sides import, + * as a client module's exports reach server code only as references. + */ +export const SEARCH_LIMIT = 20; + +export function PlayerRows({ + players, + now, + animate = true, +}: { + players: Schemas["PlayerSummary"][]; + /** One moment for every row's "ago". */ + now: Date; + /** Off for results that change as someone types: they should land at once, not fade in. */ + animate?: boolean; +}) { + const half = Math.ceil(players.length / 2); + return ( +
      + {players.map((player, index) => ( +
    • + + + + {player.name} + + {/* Most players have no country on Steam; a column of placeholders would only be noise. */} + {player.country_code && } + + {player.last_run_at ? ( + + ) : ( + // Search finds players with no 2.0 runs too. + No 2.0 runs + )} + + +
    • + ))} +
    + ); +} diff --git a/web/src/features/players/PlayerSearch.tsx b/web/src/features/players/PlayerSearch.tsx index 7126c01..61e9ab6 100644 --- a/web/src/features/players/PlayerSearch.tsx +++ b/web/src/features/players/PlayerSearch.tsx @@ -1,75 +1,56 @@ -// The Players page's search and results: players matching a name or SteamID, or recently active players. Staff -// who hold manage_bans also get a Banned tab, and staff who act on players can open a SteamID nobody has seen. -import { Search } from "lucide-react"; -import Form from "next/form"; -import type { CSSProperties } from "react"; +// The Players page's board: the search beside the title, and under it recently active players, or for staff who +// hold manage_bans a Banned tab. Loads what the first view shows; PlayerFinder answers searches as they're typed. +import type { ReactNode } from "react"; import { api } from "@/api/client"; import { signedInPlayer } from "@/features/auth/signedInPlayer"; -import { formatDate } from "@/features/runs/time"; -import { Avatar } from "@/ui/Avatar"; import { BannedPlayers } from "@/features/staff/players/BannedPlayers"; -import { Button, ButtonLink } from "@/ui/Button"; -import { Card } from "@/ui/Card"; -import { Flag } from "@/ui/Flag"; -import { Input } from "@/ui/Input"; -import { Link } from "@/ui/Link"; import { LinkTabs } from "@/ui/LinkTabs"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeaderCell, - TableRow, -} from "@/ui/Table"; import { managesPlayers } from "./PlayerHeader"; -import { STEAMID } from "./steamId"; +import { PlayerFinder } from "./PlayerFinder"; +import { PlayerRows, SEARCH_LIMIT } from "./PlayerRows"; -export async function PlayerSearch({ - q, +export async function PlayersBoard({ + q: search, banned, + heading, }: { + /** The search in the address, trimmed; empty for recently active players. */ q: string; /** The Banned tab, for staff who hold manage_bans. */ banned: boolean; + heading: ReactNode; }) { - const search = q.trim(); - const [result, me] = await Promise.all([ + const recentPlayers = () => api - .GET("/v1/players", { params: { query: search ? { q: search } : {} } }) - .catch(() => undefined), + .GET("/v1/players", { params: { query: { limit: SEARCH_LIMIT } } }) + .then((result) => result.data?.players) + .catch(() => undefined); + const [recent, found, me] = await Promise.all([ + recentPlayers(), + search + ? api + .GET("/v1/players", { + params: { query: { q: search, limit: SEARCH_LIMIT } }, + }) + .then((result) => result.data?.players) + .catch(() => undefined) + : undefined, signedInPlayer(), ]); const seesBans = me?.privileges.includes("manage_bans") ?? false; - const showBans = banned && seesBans && !search; + const showBans = banned && seesBans; + const now = new Date(); return ( -
    - {/* The search and what the list below shows share one line, the tabs at its end. */} -
    - {/* Prefetching stays off here too, as for links (docs/design-system.md). */} -
    - - -
    - - {search ? ( -

    - Players matching “{search}” -

    - ) : seesBans ? ( + ) : ( -

    Recently active

    - )} -
    +

    Latest finished run

    + ) + } + > {showBans ? ( - - ) : !result ? ( -

    Players couldn't be loaded. Try again in a moment.

    - ) : !result.data ? ( -

    - {result.error?.error ?? "That search didn't work."} +

    + +
    + ) : !recent ? ( +

    + Players couldn't be loaded. Try again in a moment. +

    + ) : recent.length === 0 ? ( +

    + Nobody has finished a run in the last 30 days.

    - ) : result.data.players.length === 0 ? ( - - {search - ? "No player has that name or SteamID." - : "Nobody has finished a run in the last 30 days."} - {STEAMID.test(search) && managesPlayers(me?.privileges) && ( - - Manage {search} anyway - - )} - ) : ( - // Keyed by the search, so every row fades in on a new search, as on the Maps page. - - - - Player - Latest run - - - - {result.data.players.map((player, index) => ( - // The name link stretches over the whole row, so the row is one click target and still a - // plain link (middle-click, keyboard) rather than a row with a click handler. - - - - - {player.name} - - - - - {player.last_run_at ? ( - - ) : ( - "None yet" - )} - - - ))} - -
    + )} -
    + ); } diff --git a/web/src/features/players/PlayerStyles.tsx b/web/src/features/players/PlayerStyles.tsx index 3e97965..0ddfa82 100644 --- a/web/src/features/players/PlayerStyles.tsx +++ b/web/src/features/players/PlayerStyles.tsx @@ -19,9 +19,11 @@ import { Badge } from "@/ui/Badge"; import { Button } from "@/ui/Button"; import { ChoiceBar } from "@/ui/ChoiceBar"; import { ChoiceMenu } from "@/ui/ChoiceMenu"; +import { Label } from "@/ui/Card"; +import { classNames } from "@/ui/classNames"; +import { CountUp } from "@/ui/CountUp"; import { Link } from "@/ui/Link"; import { Medal } from "@/ui/Medal"; -import { StatCard } from "@/ui/StatCard"; import { Table, TableBody, @@ -160,11 +162,12 @@ export function PlayerStyles({ />
    -
    - {/* Each card opens what its number comes from. The rank is the style's points leaderboard place, on - main tracks unless bonuses are shown; styles count apart, so any style has none. */} + {/* One panel of the style's standing, split into what each number opens: rank, completed maps and world + records. The rank is the style's points leaderboard place, on main tracks unless bonuses are shown; + styles count apart, so any style has none. */} +
    - + + + {standing ? : "—"} + + + {standing + ? `${numbers.format(standing.points)} points${player.points_draft ? " · draft" : ""}` + : anyStyle + ? "Ranked per style" + : "No points yet"} + - 0 ? ` · ${bonuses} ${bonuses === 1 ? "bonus" : "bonuses"}` : ""}`} - /> + + + + + + + / {numbers.format(player.map_count)} + + + {/* How far through the map list they are, with any bonuses beside; the numbers say it for screen + readers. */} + + + + + {bonuses > 0 && ( + + + {bonuses} {bonuses === 1 ? "bonus" : "bonuses"} + + )} + - {/* Every world record, newest first: any style, any track, 2.0 runs. */} + {/* Every world record, newest first: any style, any track, 2.0 runs; pressed again, back to the opening view. A + player without one has nothing to open. */} - choose({ - style: ANY, - tracks: ANY, - records: true, - }) + pressed={records} + onClick={ + counts?.world_records || records + ? () => + records + ? choose({ + style: styleKeys.find(hasTimes) ?? styleKeys[0], + tracks: "main", + records: false, + }) + : choose({ style: ANY, tracks: ANY, records: true }) + : undefined } > - + + + + + {counts?.world_records ? ( + + {records ? "Showing every record" : "Show every record"} + + ) : null}
    @@ -263,31 +317,55 @@ function withQuery( return text ? `${path}?${text}` : path; } -/** A stat card that opens a page or changes the view, entering with the cards beside it. */ +/** Rank 1 to 3 in the medal colors, as on the boards. */ +const medalText = ["text-gold", "text-silver", "text-bronze"]; + +/** + * One cell of the standing panel: opens the page its number comes from, or changes the view. With neither, + * it's a plain cell. + */ function StatLink({ href, onClick, - index, + pressed, + className, children, }: { - index: number; + href?: string; + onClick?: () => void; + /** For a cell that switches a view: whether that view is showing. */ + pressed?: boolean; + className?: string; children: ReactNode; -} & ( - { href: string; onClick?: never } | { href?: never; onClick: () => void } -)) { - // Each card fills its grid cell, so a card whose detail wraps on a phone doesn't leave its neighbor shorter. - const className = - "motion-lift motion-enter flex flex-col rounded-lg text-left *:flex-1"; - const style = { "--motion-delay": `${index * 40}ms` } as CSSProperties; - return href ? ( - - {children} - - ) : ( - +}) { + const classes = classNames("flex flex-col gap-1 p-5 text-left", className); + // The panel clips its corners, so the focus ring is drawn inside the cell. + const clickable = classNames( + classes, + "hover:bg-surface-raised transition-colors duration-(--duration-fast) focus-visible:-outline-offset-2", + // On, in the accent, as a pressed ghost button shows it. + pressed && "bg-accent-soft hover:bg-accent-soft", ); + if (href) { + return ( + + {children} + + ); + } + if (onClick) { + return ( + + ); + } + return
    {children}
    ; } /** Give it a `key` per style, tracks, view and show choice, so switching starts again from the top. */ @@ -372,7 +450,12 @@ function PersonalBests({

    These personal bests couldn't be loaded. Try again.

    - ) : null; + ) : ( + // Held in the table's place, so choosing a view that wasn't loaded with the page doesn't leave a blank. +

    + Loading… +

    + ); } const count = total ?? personalBests.length; // World records count bonuses with main tracks, so one kind of track can have none while the count doesn't. diff --git a/web/src/features/site/HeaderSearch.tsx b/web/src/features/site/HeaderSearch.tsx new file mode 100644 index 0000000..2ad2e3f --- /dev/null +++ b/web/src/features/site/HeaderSearch.tsx @@ -0,0 +1,485 @@ +"use client"; +// The header's search: players and maps as you type, in a panel under the field laid out as ok-website's is, +// each result a picture, its kind, its name and a figure. Arrow keys move through the results and Enter opens +// one; `/` anywhere jumps to the field. On narrower screens it's a button that opens the field across the header. +// +// Fast without flicker, as ok-website's: a short pause after typing before asking, each keystroke cancels the +// request still out for the old text, a sequence number drops any late reply, the results shown stay up until +// the next ones arrive, and answers are kept, so text already searched (backspacing, retyping) shows at once. +import { Search, X } from "lucide-react"; +import { usePathname, useRouter } from "next/navigation"; +import { + type KeyboardEvent, + type ReactNode, + useEffect, + useId, + useRef, + useState, +} from "react"; +import { api, type Schemas } from "@/api/client"; +import { formatSince } from "@/features/runs/time"; +import { Avatar } from "@/ui/Avatar"; +import { classNames } from "@/ui/classNames"; +import { Flag } from "@/ui/Flag"; +import { Link } from "@/ui/Link"; + +const PAUSE_MS = 110; +const SHOWN = 5; +/** Answers kept for text already searched; the oldest go first. */ +const KEPT = 40; + +interface Found { + query: string; + /** When the answer arrived, for the rows' "ago": time is read where data arrives, never while rendering. */ + at: Date; + players: Schemas["PlayerSummary"][]; + maps: Schemas["MapSummary"][]; +} + +type State = + | { status: "idle" } + | { status: "searching" } + | { status: "found"; found: Found } + | { status: "failed" }; + +export function HeaderSearch() { + const router = useRouter(); + const pathname = usePathname(); + const listId = useId(); + const input = useRef(null); + const [text, setText] = useState(""); + const [state, setState] = useState({ status: "idle" }); + const [open, setOpen] = useState(false); + /** On narrow screens the field is hidden behind a button until opened. */ + const [expanded, setExpanded] = useState(false); + const [active, setActive] = useState(-1); + const timer = useRef(undefined); + const controller = useRef(null); + const sequence = useRef(0); + const kept = useRef(new Map()); + + // `/` focuses the search from anywhere that isn't already a text field. + useEffect(() => { + function onKey(event: globalThis.KeyboardEvent) { + const target = event.target as HTMLElement; + if ( + event.key !== "/" || + event.metaKey || + event.ctrlKey || + event.altKey || + /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName) || + target.isContentEditable + ) + return; + event.preventDefault(); + setExpanded(true); + requestAnimationFrame(() => input.current?.focus()); + } + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, []); + + // A page change closes the list; what was typed stays, so going back to it is one key away. Compared during + // render, React's way to reset state when a value changes, so the old list never paints on the new page. + const [shownOn, setShownOn] = useState(pathname); + if (shownOn !== pathname) { + setShownOn(pathname); + setOpen(false); + setExpanded(false); + } + + useEffect( + () => () => { + window.clearTimeout(timer.current); + controller.current?.abort(); + }, + [], + ); + + function show(found: Found) { + setState({ status: "found", found }); + setActive(-1); + setOpen(true); + } + + function search(value: string) { + const query = value.trim(); + window.clearTimeout(timer.current); + // Abort on the keystroke, not when the pause ends: a request in flight answers text that's gone. + controller.current?.abort(); + const seq = ++sequence.current; + if (!query) { + setState({ status: "idle" }); + setOpen(false); + return; + } + const known = kept.current.get(query.toLowerCase()); + if (known) { + show(known); + return; + } + timer.current = window.setTimeout(async () => { + const abort = new AbortController(); + controller.current = abort; + // Results already up stay until the new ones land; only a first search shows "Searching". + setState((current) => + current.status === "found" ? current : { status: "searching" }, + ); + setOpen(true); + try { + const [players, maps] = await Promise.all([ + api.GET("/v1/players", { + params: { query: { q: query, limit: SHOWN } }, + signal: abort.signal, + }), + api.GET("/v1/maps", { + params: { query: { q: query, sort: "popular", limit: SHOWN } }, + signal: abort.signal, + }), + ]); + if (seq !== sequence.current) return; + if (!players.data && !maps.data) throw new Error("search failed"); + const found = { + query, + at: new Date(), + players: players.data?.players ?? [], + maps: maps.data?.maps ?? [], + }; + kept.current.set(query.toLowerCase(), found); + if (kept.current.size > KEPT) { + kept.current.delete(kept.current.keys().next().value!); + } + show(found); + } catch (error) { + if ((error as Error).name === "AbortError") return; + if (seq === sequence.current) setState({ status: "failed" }); + } + }, PAUSE_MS); + } + + const found = state.status === "found" ? state.found : null; + /** Every result in the order the arrow keys walk them: players, then maps. */ + const targets = found + ? [ + ...found.players.map((p) => `/players/${p.steamid64}`), + ...found.maps.map((m) => `/maps/${encodeURIComponent(m.name)}`), + ] + : []; + + function close() { + setOpen(false); + setActive(-1); + } + + function go(href: string) { + close(); + input.current?.blur(); + router.push(href); + } + + function onKeyDown(event: KeyboardEvent) { + if (event.key === "Escape") { + if (open) close(); + else { + input.current?.blur(); + setExpanded(false); + } + return; + } + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + if (targets.length === 0) return; + event.preventDefault(); + setOpen(true); + const step = event.key === "ArrowDown" ? 1 : -1; + // -1 is the field itself, so the keys walk field, results, field. + const slots = targets.length + 1; + setActive((at) => ((at + 1 + step + slots) % slots) - 1); + return; + } + if (event.key === "Enter") { + event.preventDefault(); + const query = text.trim(); + if (active >= 0 && targets[active]) go(targets[active]); + // No result picked: the player search page holds every match, and finds a SteamID too. + else if (query) go(`/players?q=${encodeURIComponent(query)}`); + } + } + + const optionId = (index: number) => `${listId}-${index}`; + const showList = open && state.status !== "idle"; + + return ( +
    + {/* The button that opens the field where the header has no room for it. */} + +
    +
    + + = 0 ? optionId(active) : undefined} + autoComplete="off" + spellCheck={false} + onChange={(event) => { + setText(event.target.value); + search(event.target.value); + }} + onFocus={() => { + if (text.trim()) setOpen(true); + }} + onBlur={() => { + // Late enough that a click on a result lands first. + window.setTimeout(() => { + close(); + if (!text.trim()) setExpanded(false); + }, 150); + }} + onKeyDown={onKeyDown} + className="border-border bg-surface text-text placeholder:text-text-subtle hover:border-border-strong focus:border-accent focus:bg-bg h-9 w-full rounded-lg border pr-14 pl-9 text-sm transition-colors duration-(--duration-fast) outline-none" + /> + {text ? ( + + ) : ( + + / + + )} +
    + + + {showList && ( +
    event.preventDefault()} + className="border-border-strong bg-surface-raised shadow-popover absolute top-full right-0 mt-2 max-h-120 overflow-y-auto overscroll-contain rounded-lg border p-1.5 text-sm max-xl:inset-x-4 xl:w-96" + > + {state.status === "searching" && ( +

    + Searching… +

    + )} + {state.status === "failed" && ( +

    + Search isn't available right now. Try again in a moment. +

    + )} + {found && + (found.players.length === 0 && found.maps.length === 0 ? ( +

    + No players or maps match “{found.query}”. +

    + ) : ( + <> + {found.players.length > 0 && ( + + {found.players.map((player, index) => ( + + )} + {found.maps.length > 0 && ( + + {found.maps.map((map, i) => { + const index = found.players.length + i; + return ( + + )} +
    + + All players matching “{found.query}” + + + All maps + +
    + + ))} +
    + )} +
    +
    + ); +} + +function Group({ label, children }: { label: string; children: ReactNode }) { + return ( +
    +
    + {label} +
    + {children} +
    + ); +} + +/** One result: its picture, its kind above its name, and a figure at the end, as ok-website lays them out. */ +function Option({ + id, + href, + active, + onPick, + picture, + kind, + name, + figure, +}: { + id: string; + href: string; + active: boolean; + onPick: () => void; + picture: ReactNode; + kind: string; + name: ReactNode; + figure: string; +}) { + return ( + + {picture} + + {kind} + + {name} + + + + {figure} + + + ); +} diff --git a/web/src/features/site/SignInButton.tsx b/web/src/features/site/SignInButton.tsx index 9b66024..908bef3 100644 --- a/web/src/features/site/SignInButton.tsx +++ b/web/src/features/site/SignInButton.tsx @@ -1,17 +1,15 @@ "use client"; // Sends the player to Steam to sign in, and back to this page afterwards. -import { ButtonAnchor } from "@/ui/Button"; +import { SteamButton } from "@/ui/SteamButton"; import { useReturnTo } from "./useReturnTo"; export function SignInButton() { const returnTo = useReturnTo(); return ( - // A full page load, not a client navigation: the API redirects to Steam. - - Sign in with Steam - + Sign in with Steam + ); } diff --git a/web/src/features/site/SiteFooter.tsx b/web/src/features/site/SiteFooter.tsx index 88694a5..4662dd8 100644 --- a/web/src/features/site/SiteFooter.tsx +++ b/web/src/features/site/SiteFooter.tsx @@ -1,38 +1,37 @@ -// The footer on every page: the ruleset, and SourceJump's community elsewhere. +// The footer on every page, one quiet line: the ruleset, what the site is, and SourceJump's community by their +// logos in their own colors. +import { ScrollText } from "lucide-react"; +import { BrandIcon } from "@/ui/BrandIcon"; import { Link } from "@/ui/Link"; - -/** SourceJump's own pages on other sites. The Discord invite is the one the plugin spec links to. */ -const communityLinks = [ - { label: "Discord", href: "https://discord.gg/RYP5G4tuwX" }, - { label: "YouTube", href: "https://www.youtube.com/user/SourceJump" }, - { - label: "Steam group", - href: "https://steamcommunity.com/groups/SourceJump", - }, - { label: "TikTok", href: "https://www.tiktok.com/@sourcejump.net" }, -]; +import { communityLinks } from "./navigation"; export function SiteFooter() { return ( -