From f117bcc77b4e181e91ad3460f0400ac405ce3c1a Mon Sep 17 00:00:00 2001 From: zasbu <136494048+zasbu@users.noreply.github.com> Date: Tue, 10 Nov 2026 01:47:40 +1100 Subject: [PATCH 1/3] Rework the player profile overview --- web/e2e/player-profile.e2e.ts | 128 ++++++++ web/src/app/players/[steamid]/layout.tsx | 18 +- web/src/features/players/PlayerHeader.tsx | 290 ++++++------------ web/src/features/players/PlayerProfile.tsx | 27 +- web/src/features/players/PlayerStyles.tsx | 255 +++++++++++---- .../players/ProfileHistory.module.css | 19 ++ web/src/features/players/ProfileHistory.tsx | 239 +++++++++++++++ web/src/features/players/ProfileStyleMenu.tsx | 54 ++++ .../features/players/sampleHistory.test.ts | 48 +++ web/src/features/players/sampleHistory.ts | 43 +++ 10 files changed, 840 insertions(+), 281 deletions(-) create mode 100644 web/e2e/player-profile.e2e.ts create mode 100644 web/src/features/players/ProfileHistory.module.css create mode 100644 web/src/features/players/ProfileHistory.tsx create mode 100644 web/src/features/players/ProfileStyleMenu.tsx create mode 100644 web/src/features/players/sampleHistory.test.ts create mode 100644 web/src/features/players/sampleHistory.ts diff --git a/web/e2e/player-profile.e2e.ts b/web/e2e/player-profile.e2e.ts new file mode 100644 index 0000000..e674325 --- /dev/null +++ b/web/e2e/player-profile.e2e.ts @@ -0,0 +1,128 @@ +import { expect, test } from "@playwright/test"; +import type { Schemas } from "../src/api/client"; + +test("profile stats, history controls and the table follow the selected style", async ({ + page, + request, +}) => { + const steamid = "76561199900000002"; + const response = await request.get(`/v1/players/${steamid}`); + expect(response.ok()).toBe(true); + const profile = (await response.json()) as Schemas["PlayerProfile"]; + const normal = profile.styles.find((style) => style.style === "normal")!; + await page.goto(`/players/${steamid}`); + const stats = page.getByRole("region", { + name: "Player statistics", + exact: true, + }); + await expect(stats.locator(":scope > *")).toHaveCount(6); + await expect( + stats.getByText("Global rank", { exact: true }).locator(".."), + ).toContainText(`#${normal.main_standing!.rank}`); + await expect( + stats.getByText("Top 10s", { exact: true }).locator(".."), + ).toContainText( + String( + normal.personal_bests.filter((pb) => pb.rank != null && pb.rank <= 10) + .length, + ), + ); + const history = page.getByRole("region", { + name: "Player history", + exact: true, + }); + await expect( + history.getByText("Sample history", { exact: true }), + ).toBeVisible(); + const table = page.getByRole("table"); + const before = await table.innerText(); + await history.getByRole("button", { name: /^Show/ }).click(); + await page + .getByRole("menuitemradio", { name: "Points", exact: true }) + .click(); + await expect(history.getByRole("heading")).toContainText( + "Points, last 12 months", + ); + expect(await table.innerText()).toBe(before); + const graph = history.getByRole("img"); + await graph.focus(); + await page.keyboard.press("Home"); + await expect(history.locator('[aria-live="polite"]')).toContainText("Dec"); + await page.evaluate(() => { + (window as { profileStayed?: boolean }).profileStayed = true; + }); + await page.getByRole("button", { name: /^Style / }).click(); + await page + .getByRole("menuitemradio", { name: "Scroll", exact: true }) + .click(); + await expect(page).toHaveURL(/style=scroll/); + await expect(history.getByRole("heading")).toContainText( + "Points, last 12 months · Scroll", + ); + expect( + await page.evaluate( + () => (window as { profileStayed?: boolean }).profileStayed, + ), + ).toBe(true); + await page.getByRole("button", { name: /^Style / }).click(); + await page.getByRole("menuitemradio", { name: "Any", exact: true }).click(); + await expect( + stats.getByText("Global rank", { exact: true }).locator(".."), + ).toContainText(`#${normal.main_standing!.rank}`); + await page.getByRole("button", { name: /^Style / }).click(); + await page + .getByRole("menuitemradio", { name: "Autosync", exact: true }) + .click(); + await expect( + stats.getByText("Global rank", { exact: true }).locator(".."), + ).toContainText("—"); + await expect( + history.getByText(/history isn't available for this player/), + ).toBeVisible(); +}); + +test("profile containers fit desktop and narrow phones", async ({ page }) => { + await page.goto("/players/76561199900000002"); + await expect(page.getByRole("heading", { level: 1 })).toBeVisible(); + for (const width of [1920, 1024, 768, 390, 320]) { + await page.setViewportSize({ width, height: 1000 }); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth > innerWidth, + ), + ).toBe(false); + const columns = await page + .getByRole("region", { name: "Player statistics" }) + .evaluate( + (element) => + getComputedStyle(element).gridTemplateColumns.split(" ").length, + ); + expect(columns).toBe(width < 640 ? 2 : 3); + } + expect( + await page + .locator("clipPath rect") + .evaluate((element) => getComputedStyle(element).animationName), + ).toBe("none"); +}); + +test("history reveals from left to right when motion is enabled", async ({ + page, +}) => { + await page.emulateMedia({ reducedMotion: "no-preference" }); + await page.goto("/players/76561199900000002"); + const scales = await page.locator("clipPath rect").evaluate((element) => { + const animation = element.getAnimations()[0]!; + animation.pause(); + const values = [0, 450, 900].map((time) => { + animation.currentTime = time; + return new DOMMatrix(getComputedStyle(element).transform).a; + }); + animation.finish(); + return values; + }); + expect(scales[0]).toBe(0); + expect(scales[1]).toBeGreaterThan(0); + expect(scales[1]).toBeLessThan(1); + expect(scales[2]).toBe(1); +}); diff --git a/web/src/app/players/[steamid]/layout.tsx b/web/src/app/players/[steamid]/layout.tsx index e90354d..46c5e2c 100644 --- a/web/src/app/players/[steamid]/layout.tsx +++ b/web/src/app/players/[steamid]/layout.tsx @@ -1,20 +1,26 @@ -// A player's pages: the masthead stays while the profile and the Manage view swap beneath it. +// A player's identity stays while the profile and Manage view swap beneath it. import { PlayerHeader } from "@/features/players/PlayerHeader"; import { Page } from "@/ui/Page"; +import { Link } from "@/ui/Link"; +import { ArrowLeft } from "lucide-react"; export default function PlayerLayout({ params, children, }: LayoutProps<"/players/[steamid]">) { return ( - // The masthead runs edge to edge, so the page sets its own width below it. - + + + + Leaderboards + {params.then(({ steamid }) => ( ))} -
- {children} -
+
{children}
); } diff --git a/web/src/features/players/PlayerHeader.tsx b/web/src/features/players/PlayerHeader.tsx index e365aea..bbe97ce 100644 --- a/web/src/features/players/PlayerHeader.tsx +++ b/web/src/features/players/PlayerHeader.tsx @@ -1,34 +1,24 @@ -// The top of a player's pages, a masthead across the page: avatar, name, flag, country, first and latest run -// and Steam profile link, their rank in the style shown below, and the Profile / Manage switch for staff. -// Behind it, the map of their latest world record (or latest run), captioned as such. It sits in the player's -// layout, so switching to the Manage view keeps it. +// A player's identity, with the profile's style choice and staff view switch. import { ExternalLink } from "lucide-react"; import { notFound } from "next/navigation"; -import { api, type Schemas } from "@/api/client"; +import 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, - trackName, -} from "@/features/runs/time"; -import { classNames } from "@/ui/classNames"; -import { Link } from "@/ui/Link"; -import { Masthead, type MastheadImage } from "@/ui/Masthead"; +import { formatDate, formatSince } from "@/features/runs/time"; import { currentStyles } from "@/features/ruleset/styles"; import { getPlayer } from "./playerDetail"; -import { ProfileRank } from "./ProfileRank"; -import { avatarSrc } from "@/features/players/avatarSrc"; +import { ProfileStyleMenu } from "./ProfileStyleMenu"; +import { avatarSrc } from "./avatarSrc"; export async function PlayerHeader({ steamid }: { steamid: string }) { - const [result, me] = await Promise.all([ + const [result, me, styles] = await Promise.all([ getPlayer(steamid), signedInPlayer(), + currentStyles(), ]); const manager = managesPlayers(me?.privileges); const staffResult = manager ? await getStaffPlayer(steamid) : undefined; @@ -37,209 +27,107 @@ export async function PlayerHeader({ steamid }: { steamid: string }) { const profile = result?.data; const player: Schemas["PlayerRef"] | undefined = profile ?? staffView?.player; if (!player) { - if (result?.response.status === 404 || result?.response.status === 422) { + if (result?.response.status === 404 || result?.response.status === 422) notFound(); - } return null; } - const isOwn = me?.steamid64 === player.steamid64; + const own = 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, styles] = await Promise.all([ - profile && featuredRun(profile), - currentStyles(), - ]); - const image = featured && (await mapCover(featured.pb.map)); - - const rank = - profile && - ((inline = false) => ( - [key, styles.name(key)]), - )} - draft={profile.points_draft} - inline={inline} - /> - )); + const account = BigInt(player.steamid64) - 76561197960265728n; + const steamId = `STEAM_1:${account % 2n}:${account / 2n}`; return ( - // Less of the picture above the name on a phone, and a smaller avatar, so the profile starts sooner. - - <> -
- + +
+
+

+ {player.name} +

+ {banned && Banned} +
+
+ -
- {/* 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 - - )} -
- {rank &&
{rank(true)}
} - {/* 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 - - + {country && {country}} +
+ + {steamId} + + Steam profile + +
+ {profile?.first_run_at && ( +
+
First 2.0 run
+
+ +
-
- {/* A player SourceJump hasn't seen has no profile to switch to. */} - {manager && profile && ( - )} - {/* Their rank, the main thing a profile tells, for the style the profile below shows: large at the row's - end; on a phone, the line under the name. */} - {rank && ( -
{rank()}
+ {profile?.last_run_at && ( +
+
Latest run
+
+ +
+
)} -
- {/* What the picture is, on the picture: which run of theirs it's the map of. Outside the header, whose - entrance transform would make it the box this is placed in. */} - {image && featured && ( -
- {/* The same frosted plate as a server row's labels on its map picture: the picture shows through, softened. */} -

- {featured.label} - · - 0 ? `&track=${featured.pb.track}` : ""}`} - className="text-text hover:text-accent truncate font-bold" - > - {featured.pb.map} - - - {[ - featured.pb.track > 0 && trackName(featured.pb.track), - styles.name(featured.pb.style), - formatTime(featured.pb.time), - ] - .filter(Boolean) - .join(" · ")} - -

-
+ + +
+ {manager && profile && ( + + )} + {profile && ( + [key, styles.name(key)]), + )} + /> )} - - +
+ ); } -/** - * The run whose map stands behind the header: their latest world record, or with none, their latest run. Asked of - * the API rather than picked from the profile, whose personal bests are only each style's first page. - */ -async function featuredRun( - profile: Schemas["PlayerProfile"], -): Promise<{ pb: Schemas["PersonalBest"]; label: string } | undefined> { - const records = profile.all_styles.world_records > 0; - const result = await api - .GET("/v1/players/{player}/personal-bests", { - params: { - path: { player: profile.steamid64 }, - // Without a style: every style, most recently finished first. - query: { records: records || undefined, limit: 1 }, - }, - }) - .catch(() => undefined); - const pb = result?.data?.personal_bests[0]; - if (!pb) return undefined; - return { - pb, - label: records ? "Latest world record" : "Latest personal 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. */ +/** Staff permissions are checked again by the API. */ export function managesPlayers( privileges: readonly Schemas["Privilege"][] | undefined, ): boolean { diff --git a/web/src/features/players/PlayerProfile.tsx b/web/src/features/players/PlayerProfile.tsx index db8542d..30b60e0 100644 --- a/web/src/features/players/PlayerProfile.tsx +++ b/web/src/features/players/PlayerProfile.tsx @@ -1,17 +1,27 @@ // A player's profile, under their header: their details, then per style their stats and personal bests. import { notFound, redirect } from "next/navigation"; +import { api } from "@/api/client"; import { signedInPlayer } from "@/features/auth/signedInPlayer"; import { currentStyles } from "@/features/ruleset/styles"; import { Card } from "@/ui/Card"; import { getPlayer } from "./playerDetail"; import { PlayerDetails } from "./PlayerDetails"; import { PlayerStyles } from "./PlayerStyles"; +import { sampleHistory } from "./sampleHistory"; export async function PlayerProfile({ steamid }: { steamid: string }) { - const [result, styles, me] = await Promise.all([ + const [result, styles, me, bonusBoard] = await Promise.all([ getPlayer(steamid), currentStyles(), signedInPlayer(), + api + .GET("/v1/leaderboards/{ranking}", { + params: { + path: { ranking: "completed" }, + query: { track: "bonuses", limit: 1 }, + }, + }) + .catch(() => undefined), ]); if (!result) { @@ -31,15 +41,20 @@ export async function PlayerProfile({ steamid }: { steamid: string }) { return ( <> - {player.styles.length === 0 && player.legacy_maps === 0 ? ( - - No personal bests yet. They show here once a run is finished on a - SourceJump server. - + <> + + + No personal bests yet. They show here once a run is finished on a + SourceJump server. + + ) : ( } + history={sampleHistory(player)} + bonusTotal={bonusBoard?.data?.out_of} styleOrder={styles.keys} styleNames={Object.fromEntries( styles.keys.map((k) => [k, styles.name(k)]), diff --git a/web/src/features/players/PlayerStyles.tsx b/web/src/features/players/PlayerStyles.tsx index 3e6bb03..fd0ea79 100644 --- a/web/src/features/players/PlayerStyles.tsx +++ b/web/src/features/players/PlayerStyles.tsx @@ -4,7 +4,23 @@ // arrives with the profile, so switching styles happens in place; bonuses, world records and the normal // style's pre-2.0 views load when chosen. The counts are 2.0's in every view. import { useSearchParams } from "next/navigation"; -import { type CSSProperties, type ReactNode, useEffect, useState } from "react"; +import { + type CSSProperties, + type ReactNode, + useCallback, + useEffect, + useState, +} from "react"; +import { + Globe, + Trophy, + Medal as MedalIcon, + Star, + Map as MapIcon, + Gem, +} from "lucide-react"; +import { ProfileHistory } from "./ProfileHistory"; +import type { ProfileHistoryPoint } from "./sampleHistory"; import { api, type Schemas } from "@/api/client"; import { LegacyBadge } from "@/features/legacy/LegacyBadge"; import { ReplayLink } from "@/features/replays/ReplayLink"; @@ -49,7 +65,6 @@ import { const PAGE_SIZE = 50; const numbers = new Intl.NumberFormat("en"); -const percent = new Intl.NumberFormat("en", { style: "percent" }); /** The Style and Track menus' choice of every style or every track. */ const ANY = "any"; @@ -59,13 +74,28 @@ export function PlayerStyles({ player, styleOrder, styleNames, + history, + details, + bonusTotal, }: { player: Schemas["PlayerProfile"]; /** Style keys in the ruleset's order. */ styleOrder: string[]; styleNames: Record; + history?: Record; + details?: ReactNode; + bonusTotal?: number; }) { const params = useSearchParams(); + const choiceKey = params.toString(); + const [loaded, setLoaded] = useState<{ + key: string; + rows: Schemas["PersonalBest"][]; + }>(); + const acceptRows = useCallback( + (rows: Schemas["PersonalBest"][]) => setLoaded({ key: choiceKey, rows }), + [choiceKey], + ); const hasLegacy = player.legacy_maps > 0; const tracksParam = params.get("tracks"); const tracks: Tracks = @@ -105,6 +135,38 @@ export function PlayerStyles({ const boardStyle = anyStyle || styleKey === styleOrder[0] ? {} : { style: styleKey }; + const ranked = anyStyle + ? styleKeys + .map(summary) + .find( + (style) => + style && + (tracks === "bonuses" ? style.bonus_standing : style.main_standing), + ) + : current; + const standing = + tracks === "bonuses" ? ranked?.bonus_standing : ranked?.main_standing; + const historyStyle = ranked?.style ?? styleKey; + const historyName = `${styleNames[historyStyle] ?? historyStyle}${tracks === "bonuses" ? " bonuses" : ""}`; + const rows = loaded?.key === choiceKey ? loaded.rows : undefined; + const completeFirst = + tracks === "main" && !records && current && !current.next_cursor + ? current.personal_bests + : undefined; + const top10 = + view !== "current" + ? undefined + : !shownTotal + ? 0 + : (rows ?? completeFirst)?.filter( + (pb) => pb.rank != null && pb.rank <= 10, + ).length; + const pointsStyle = ranked?.style ?? (anyStyle ? styleOrder[0] : styleKey); + const pointsHref = withQuery("/leaderboards/points", { + style: pointsStyle !== styleOrder[0] ? pointsStyle : undefined, + ...(tracks === "bonuses" && { track: "bonuses" }), + }); + // The choice lives in the address, so a view can be shared, but changing it doesn't load a page. function choose(choice: { style?: string; @@ -126,51 +188,19 @@ export function PlayerStyles({ return ( <> - {/* The style's progress, split into what each number opens: completed maps and world records, compact like the - home page's numbers. The rank leads the header above. */} -
- +
+ + Global rank + + + - - - {" "} - / {numbers.format(player.map_count)} - + {standing ? `#${numbers.format(standing.rank)}` : "—"} - - completed maps - {bonuses > 0 && ( - - {` · ${bonuses} ${bonuses === 1 ? "bonus" : "bonuses"}`} - - )} - - {player.map_count > 0 && ( - - {percent.format(maps / player.map_count)} - - )} - {/* How far through the map list they are, along the cell's foot; the numbers say it for screen readers. */} - - - - {/* 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. */} + World records + + + - world records - {counts?.world_records ? ( - - {records ? "Showing all" : "Show all"} + + + Top 10s + + + + + {top10 === undefined ? "—" : numbers.format(top10)} + + + + Points + + + + + + + + + Maps completed + + + + + + + {" "} + / {numbers.format(player.map_count)} + + + {player.map_count > 0 && ( + + - ) : null} + )} -
+ + Bonuses completed + + + + + + {bonusTotal != null && ( + + {" "} + / {numbers.format(bonusTotal)} + + )} + + {bonusTotal != null && bonusTotal > 0 && ( + + + + )} + + + + {details} {/* The choices sit with the list they narrow, under the overview. */}
- ({ - value: key, - label: styleNames[key] ?? key, - quiet: !hasTimes(key), - startsGroup: index === 0, - })), - ]} - value={styleKey} - onChange={(style) => choose({ style })} - /> styleNames[key] ?? key} tracks={tracks === ANY ? undefined : tracks} @@ -324,9 +426,8 @@ function StatLink({ className?: string; children: ReactNode; }) { - // Number over its words on narrow screens, side by side from lg, as the home page's numbers. const classes = classNames( - "group relative flex min-w-0 flex-col px-3 py-2 text-left sm:px-4 sm:py-3 lg:flex-row lg:items-baseline lg:gap-2", + "group border-border bg-surface relative flex min-h-28 min-w-0 flex-col gap-3 overflow-hidden rounded-md border p-4 text-left sm:p-5", className, ); // The panel clips its corners, so the focus ring is drawn inside the cell. @@ -369,7 +470,7 @@ function StatValue({ return ( @@ -381,7 +482,18 @@ function StatValue({ /** What a standing cell's number counts. */ function StatText({ children }: { children: ReactNode }) { return ( - + + {children} + + ); +} + +function StatIcon({ children }: { children: ReactNode }) { + return ( + {children} ); @@ -398,6 +510,7 @@ function PersonalBests({ first, total, tierCount, + onLoaded, }: { steamid64: string; /** Left out for every style, listed most recently finished first. */ @@ -414,6 +527,7 @@ function PersonalBests({ total?: number; /** Tiers in force, for the badges; undefined until the community sets tiers. */ tierCount?: number; + onLoaded: (rows: Schemas["PersonalBest"][]) => void; }) { // The API's own order: by map in one style, newest first across styles. const apiOrder: PbSort = style @@ -527,6 +641,11 @@ function PersonalBests({ // eslint-disable-next-line react-hooks/exhaustive-deps -- the key remounts this for another style or view }, []); + useEffect(() => { + if (personalBests && !cursor && !loading && !failed) + onLoaded(personalBests); + }, [personalBests, cursor, loading, failed, onLoaded]); + if (!personalBests) { return failed ? (

diff --git a/web/src/features/players/ProfileHistory.module.css b/web/src/features/players/ProfileHistory.module.css new file mode 100644 index 0000000..10bf78a --- /dev/null +++ b/web/src/features/players/ProfileHistory.module.css @@ -0,0 +1,19 @@ +.reveal { + transform-origin: 0 0; + animation: history-reveal 900ms var(--ease-out) both; +} + +@keyframes history-reveal { + from { + transform: scaleX(0); + } + to { + transform: scaleX(1); + } +} + +@media (prefers-reduced-motion: reduce) { + .reveal { + animation: none; + } +} diff --git a/web/src/features/players/ProfileHistory.tsx b/web/src/features/players/ProfileHistory.tsx new file mode 100644 index 0000000..8c6afeb --- /dev/null +++ b/web/src/features/players/ProfileHistory.tsx @@ -0,0 +1,239 @@ +"use client"; + +import { useId, useState, type KeyboardEvent, type PointerEvent } from "react"; +import { ChoiceMenu } from "@/ui/ChoiceMenu"; +import { formatDate } from "@/features/runs/time"; +import type { ProfileHistoryPoint } from "./sampleHistory"; +import styles from "./ProfileHistory.module.css"; + +const number = new Intl.NumberFormat("en"); +const compact = new Intl.NumberFormat("en", { + notation: "compact", + maximumFractionDigits: 1, +}); +const month = new Intl.DateTimeFormat("en", { + month: "short", + timeZone: "UTC", +}); +const W = 1000; +const H = 220; + +export function ProfileHistory({ + series, + styleName, +}: { + series?: ProfileHistoryPoint[]; + styleName: string; +}) { + const [metric, setMetric] = useState<"rank" | "points">("rank"); + const [active, setActive] = useState(null); + const id = useId(); + const title = metric === "rank" ? "Rank" : "Points"; + const format = (value: number) => + metric === "rank" ? `#${number.format(value)}` : number.format(value); + const values = series?.map((point) => point[metric]) ?? []; + const min = + metric === "rank" && values.length + ? Math.max(1, Math.min(...values) - 1) + : 0; + const max = Math.max(min + 4, ...values); + const y = (value: number) => + (metric === "rank" + ? (value - min) / (max - min) + : (max - value) / (max - min)) * H; + const coords = + series?.map((point, index) => ({ + x: (index / (series.length - 1)) * W, + y: y(point[metric]), + })) ?? []; + const path = coords + .map((point, index) => { + if (!index) return `M${point.x},${point.y}`; + const previous = coords[index - 1]!; + const mid = (previous.x + point.x) / 2; + return `C${mid},${previous.y} ${mid},${point.y} ${point.x},${point.y}`; + }) + .join(" "); + const ticks = Array.from({ length: 5 }, (_, i) => + Math.round(min + ((max - min) * i) / 4), + ); + const selected = active === null ? undefined : series?.[active]; + + function nearest(event: PointerEvent) { + const bounds = event.currentTarget.getBoundingClientRect(); + setActive( + Math.max( + 0, + Math.min( + coords.length - 1, + Math.round( + ((event.clientX - bounds.left) / bounds.width) * + (coords.length - 1), + ), + ), + ), + ); + } + function navigate(event: KeyboardEvent) { + const current = active ?? coords.length - 1; + const next = { + ArrowLeft: current - 1, + ArrowRight: current + 1, + Home: 0, + End: coords.length - 1, + }[event.key]; + if (next === undefined) return; + event.preventDefault(); + setActive(Math.max(0, Math.min(coords.length - 1, next))); + } + + return ( +

+
+

+ {title}, last 12 months · {styleName} +

+ + setMetric(value === "points" ? "points" : "rank") + } + /> +
+ {series && series.length > 1 ? ( + <> +

+ {selected + ? `${formatDate(selected.date)} · ${format(selected[metric])} · sample history` + : "Sample history"} +

+
+
+ {ticks.map((tick) => ( + + {metric === "rank" ? `#${tick}` : compact.format(tick)} + + ))} +
+
+
setActive(null)} + onFocus={() => setActive(coords.length - 1)} + onBlur={() => setActive(null)} + onKeyDown={navigate} + className="focus-visible:ring-accent relative h-48 cursor-crosshair touch-pan-y rounded-sm outline-none focus-visible:ring-2 sm:h-60" + > + + + + + + + + + + + {ticks.map((tick) => ( + + ))} + + + + + + {active !== null && coords[active] && ( + + )} +
+
+ {series.map((point, index) => ( + + {month.format(new Date(point.date))} + + ))} +
+
+
+ + ) : ( +

+ {title} history isn't available for this player yet. +

+ )} +
+ ); +} diff --git a/web/src/features/players/ProfileStyleMenu.tsx b/web/src/features/players/ProfileStyleMenu.tsx new file mode 100644 index 0000000..3432944 --- /dev/null +++ b/web/src/features/players/ProfileStyleMenu.tsx @@ -0,0 +1,54 @@ +"use client"; + +import { usePathname, useSearchParams } from "next/navigation"; +import type { Schemas } from "@/api/client"; +import { ChoiceMenu } from "@/ui/ChoiceMenu"; +import { LEGACY_STYLE } from "@/features/legacy/views"; + +export function ProfileStyleMenu({ + player, + styleOrder, + styleNames, +}: { + player: Schemas["PlayerProfile"]; + styleOrder: string[]; + styleNames: Record; +}) { + const params = useSearchParams(); + const pathname = usePathname(); + const keys = [ + ...styleOrder, + ...player.styles + .map((s) => s.style) + .filter((key) => !styleOrder.includes(key)), + ]; + const hasTimes = (key: string) => + player.styles.some((s) => s.style === key) || + (key === LEGACY_STYLE && player.legacy_maps > 0); + const selected = + ["any", ...keys].find((key) => key === params.get("style")) ?? + keys.find(hasTimes) ?? + keys[0]; + if (!selected || pathname.endsWith("/manage")) return null; + return ( + ({ + value: key, + label: styleNames[key] ?? key, + quiet: !hasTimes(key), + startsGroup: index === 0, + })), + ]} + onChange={(style) => { + const url = new URL(window.location.href); + url.searchParams.set("style", style); + url.searchParams.delete("view"); + window.history.replaceState(null, "", url); + }} + /> + ); +} diff --git a/web/src/features/players/sampleHistory.test.ts b/web/src/features/players/sampleHistory.test.ts new file mode 100644 index 0000000..f321e1d --- /dev/null +++ b/web/src/features/players/sampleHistory.test.ts @@ -0,0 +1,48 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { sampleHistory } from "./sampleHistory"; + +const player = { + steamid64: "76561199900000002", + styles: [ + { + style: "normal", + main_standing: { rank: 9, points: 43613 }, + bonus_standing: null, + completed_maps: 10, + completed_bonuses: 4, + world_records: 1, + personal_bests: [], + }, + ], +}; +const now = new Date("2026-11-10T12:00:00Z"); +afterEach(() => vi.unstubAllEnvs()); + +it("provides twelve sample months ending at the mock player's current standing", () => { + vi.stubEnv("NODE_ENV", "development"); + vi.stubEnv("SJ_API_URL", "http://127.0.0.1:8080"); + const points = sampleHistory(player, now)!["normal:main"]!; + expect(points).toHaveLength(12); + expect(points[0]!.date).toBe("2025-12-01T00:00:00.000Z"); + expect(points.at(-1)).toEqual({ + date: "2026-11-01T00:00:00.000Z", + rank: 9, + points: 43613, + }); +}); + +it("never generates history for real players", () => { + vi.stubEnv("NODE_ENV", "development"); + vi.stubEnv("SJ_API_URL", "http://localhost:8080"); + expect( + sampleHistory({ ...player, steamid64: "76561198000000001" }, now), + ).toBeUndefined(); +}); + +it("never exposes sample history in production or when using beta data", () => { + vi.stubEnv("NODE_ENV", "production"); + expect(sampleHistory(player, now)).toBeUndefined(); + vi.stubEnv("NODE_ENV", "development"); + vi.stubEnv("SJ_API_URL", "https://beta.sourcejump.net"); + expect(sampleHistory(player, now)).toBeUndefined(); +}); diff --git a/web/src/features/players/sampleHistory.ts b/web/src/features/players/sampleHistory.ts new file mode 100644 index 0000000..098876d --- /dev/null +++ b/web/src/features/players/sampleHistory.ts @@ -0,0 +1,43 @@ +import type { Schemas } from "@/api/client"; + +export interface ProfileHistoryPoint { + date: string; + rank: number; + points: number; +} + +/** Development fixtures only: never manufacture history for real players or production. */ +export function sampleHistory( + player: Pick, + now = new Date(), +) { + const local = new URL(process.env.SJ_API_URL ?? "http://127.0.0.1:8080"); + const id = BigInt(player.steamid64); + if ( + process.env.NODE_ENV !== "development" || + !["localhost", "127.0.0.1", "[::1]"].includes(local.hostname) || + id < 76561199900000001n || + id > 76561199900000060n + ) + return undefined; + const progress = [0, 0, 0.25, 0.3, 0.44, 0.53, 0.6, 0.64, 0.86, 0.9, 0.88, 1]; + const result: Record = {}; + for (const style of player.styles) { + for (const [track, standing] of [ + ["main", style.main_standing], + ["bonuses", style.bonus_standing], + ] as const) { + if (!standing) continue; + result[`${style.style}:${track}`] = progress.map((value, month) => ({ + date: new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 11 + month, 1), + ).toISOString(), + rank: Math.round( + standing.rank + (1 - value) * Math.max(20, standing.rank * 2), + ), + points: Math.round(standing.points * (0.35 + value * 0.65)), + })); + } + } + return result; +} From 803fb110b4062ad22d0eae57509b92f541aa5ad5 Mon Sep 17 00:00:00 2001 From: zasbu <136494048+zasbu@users.noreply.github.com> Date: Tue, 10 Nov 2026 02:03:05 +1100 Subject: [PATCH 2/3] Add profile stat colours and world record history --- web/e2e/player-profile.e2e.ts | 15 ++++- .../features/players/PlayerStyles.module.css | 17 ++++++ web/src/features/players/PlayerStyles.tsx | 55 ++++++++++--------- web/src/features/players/ProfileHistory.tsx | 24 ++++++-- .../features/players/sampleHistory.test.ts | 1 + web/src/features/players/sampleHistory.ts | 2 + web/src/ui/tokens.css | 5 ++ 7 files changed, 87 insertions(+), 32 deletions(-) create mode 100644 web/src/features/players/PlayerStyles.module.css diff --git a/web/e2e/player-profile.e2e.ts b/web/e2e/player-profile.e2e.ts index e674325..7a85a73 100644 --- a/web/e2e/player-profile.e2e.ts +++ b/web/e2e/player-profile.e2e.ts @@ -48,6 +48,19 @@ test("profile stats, history controls and the table follow the selected style", await graph.focus(); await page.keyboard.press("Home"); await expect(history.locator('[aria-live="polite"]')).toContainText("Dec"); + await history.getByRole("button", { name: /^Show/ }).click(); + await page + .getByRole("menuitemradio", { name: "World records", exact: true }) + .click(); + await expect(history.getByRole("heading")).toContainText( + "World records, last 12 months · Normal · All tracks", + ); + expect(await table.innerText()).toBe(before); + await graph.focus(); + await page.keyboard.press("End"); + await expect(history.locator('[aria-live="polite"]')).toContainText( + ` · ${normal.world_records} · sample history`, + ); await page.evaluate(() => { (window as { profileStayed?: boolean }).profileStayed = true; }); @@ -57,7 +70,7 @@ test("profile stats, history controls and the table follow the selected style", .click(); await expect(page).toHaveURL(/style=scroll/); await expect(history.getByRole("heading")).toContainText( - "Points, last 12 months · Scroll", + "World records, last 12 months · Scroll · All tracks", ); expect( await page.evaluate( diff --git a/web/src/features/players/PlayerStyles.module.css b/web/src/features/players/PlayerStyles.module.css new file mode 100644 index 0000000..4628032 --- /dev/null +++ b/web/src/features/players/PlayerStyles.module.css @@ -0,0 +1,17 @@ +.stat { + background-image: radial-gradient( + ellipse at 100% 0%, + color-mix(in srgb, var(--stat-color) 12%, transparent), + transparent 70% + ); +} + +.icon { + color: var(--stat-color); + background-color: color-mix(in srgb, var(--stat-color) 20%, transparent); + box-shadow: 0 0 20px color-mix(in srgb, var(--stat-color) 12%, transparent); +} + +.progress { + background-color: var(--stat-color); +} diff --git a/web/src/features/players/PlayerStyles.tsx b/web/src/features/players/PlayerStyles.tsx index fd0ea79..c4b9c29 100644 --- a/web/src/features/players/PlayerStyles.tsx +++ b/web/src/features/players/PlayerStyles.tsx @@ -21,6 +21,7 @@ import { } from "lucide-react"; import { ProfileHistory } from "./ProfileHistory"; import type { ProfileHistoryPoint } from "./sampleHistory"; +import styles from "./PlayerStyles.module.css"; import { api, type Schemas } from "@/api/client"; import { LegacyBadge } from "@/features/legacy/LegacyBadge"; import { ReplayLink } from "@/features/replays/ReplayLink"; @@ -147,7 +148,7 @@ export function PlayerStyles({ const standing = tracks === "bonuses" ? ranked?.bonus_standing : ranked?.main_standing; const historyStyle = ranked?.style ?? styleKey; - const historyName = `${styleNames[historyStyle] ?? historyStyle}${tracks === "bonuses" ? " bonuses" : ""}`; + const historyName = styleNames[historyStyle] ?? historyStyle; const rows = loaded?.key === choiceKey ? loaded.rows : undefined; const completeFirst = tracks === "main" && !records && current && !current.next_cursor @@ -192,7 +193,7 @@ export function PlayerStyles({ aria-label="Player statistics" className="motion-enter grid grid-cols-2 gap-3 sm:grid-cols-3" > - + Global rank @@ -202,6 +203,7 @@ export function PlayerStyles({ - + - + Top 10s @@ -233,7 +235,7 @@ export function PlayerStyles({ {top10 === undefined ? "—" : numbers.format(top10)} - + Points @@ -243,6 +245,7 @@ export function PlayerStyles({ )} - + Bonuses completed @@ -294,7 +297,7 @@ export function PlayerStyles({ className="bg-surface-overlay absolute inset-x-0 bottom-0 h-1" > {details} @@ -416,6 +420,7 @@ function StatLink({ href, onClick, pressed, + color, className, children, }: { @@ -423,13 +428,16 @@ function StatLink({ onClick?: () => void; /** For a cell that switches a view: whether that view is showing. */ pressed?: boolean; + color: string; className?: string; children: ReactNode; }) { const classes = classNames( "group border-border bg-surface relative flex min-h-28 min-w-0 flex-col gap-3 overflow-hidden rounded-md border p-4 text-left sm:p-5", + styles.stat, className, ); + const style = { "--stat-color": color } as CSSProperties; // The panel clips its corners, so the focus ring is drawn inside the cell. const clickable = classNames( classes, @@ -439,7 +447,7 @@ function StatLink({ ); if (href) { return ( - + {children} ); @@ -451,29 +459,23 @@ function StatLink({ onClick={onClick} aria-pressed={pressed} className={clickable} + style={style} > {children} ); } - return
{children}
; + return ( +
+ {children} +
+ ); } -/** A standing cell's number: in its own color (a medal, the record accent), or the accent on hover as at home. */ -function StatValue({ - color, - children, -}: { - color?: string; - children: ReactNode; -}) { +/** A standing cell's number, accented on hover as at home. */ +function StatValue({ children }: { children: ReactNode }) { return ( - + {children} ); @@ -492,7 +494,10 @@ function StatIcon({ children }: { children: ReactNode }) { return ( {children} diff --git a/web/src/features/players/ProfileHistory.tsx b/web/src/features/players/ProfileHistory.tsx index 8c6afeb..6ef553a 100644 --- a/web/src/features/players/ProfileHistory.tsx +++ b/web/src/features/players/ProfileHistory.tsx @@ -21,14 +21,23 @@ const H = 220; export function ProfileHistory({ series, styleName, + bonuses = false, }: { series?: ProfileHistoryPoint[]; styleName: string; + bonuses?: boolean; }) { - const [metric, setMetric] = useState<"rank" | "points">("rank"); + const [metric, setMetric] = useState<"rank" | "points" | "worldRecords">( + "rank", + ); const [active, setActive] = useState(null); const id = useId(); - const title = metric === "rank" ? "Rank" : "Points"; + const title = { + rank: "Rank", + points: "Points", + worldRecords: "World records", + }[metric]; + const context = `${styleName}${metric === "worldRecords" ? " · All tracks" : bonuses ? " bonuses" : ""}`; const format = (value: number) => metric === "rank" ? `#${number.format(value)}` : number.format(value); const values = series?.map((point) => point[metric]) ?? []; @@ -94,7 +103,7 @@ export function ProfileHistory({ >

- {title}, last 12 months · {styleName} + {title}, last 12 months · {context}

- setMetric(value === "points" ? "points" : "rank") + setMetric( + value === "points" || value === "worldRecords" ? value : "rank", + ) } />
@@ -133,7 +145,7 @@ export function ProfileHistory({
Date: Tue, 10 Nov 2026 02:15:31 +1100 Subject: [PATCH 3/3] Make profile stats clickable and refine hover states --- web/e2e/player-profile.e2e.ts | 98 +++++++++++ .../features/players/PlayerStyles.module.css | 80 +++++++++ web/src/features/players/PlayerStyles.tsx | 163 +++++++++++------- 3 files changed, 275 insertions(+), 66 deletions(-) diff --git a/web/e2e/player-profile.e2e.ts b/web/e2e/player-profile.e2e.ts index 7a85a73..1b8381c 100644 --- a/web/e2e/player-profile.e2e.ts +++ b/web/e2e/player-profile.e2e.ts @@ -94,6 +94,104 @@ test("profile stats, history controls and the table follow the selected style", ).toBeVisible(); }); +test("stat cards open the player's matching progress without changing style", async ({ + page, + request, +}) => { + const steamid = "76561199900000002"; + const profile = (await ( + await request.get(`/v1/players/${steamid}`) + ).json()) as Schemas["PlayerProfile"]; + const normal = profile.styles.find((style) => style.style === "normal")!; + const bonuses = (await ( + await request.get( + `/v1/players/${steamid}/personal-bests?style=normal&tracks=bonuses&limit=100`, + ) + ).json()) as Schemas["PersonalBestPage"]; + expect(bonuses.next_cursor).not.toBeTruthy(); + await page.goto(`/players/${steamid}`); + const stats = page.getByRole("region", { name: "Player statistics" }); + const times = page.getByRole("region", { name: "Player times" }); + const card = (name: string) => + stats.getByRole("button", { name: new RegExp(`^${name}`) }); + const top10 = normal.personal_bests.filter( + (pb) => pb.rank != null && pb.rank <= 10, + ); + const all = [...normal.personal_bests, ...bonuses.personal_bests]; + + async function expectRuns(pbs: Schemas["PersonalBest"][]) { + await expect(times.locator("tbody tr")).toHaveCount(pbs.length); + expect( + await times + .locator('tbody a[href^="/maps/"]') + .evaluateAll((links) => + links.map((a) => a.getAttribute("href")).sort(), + ), + ).toEqual( + pbs + .map( + (pb) => + `/maps/${pb.map}?style=${pb.style}${pb.track > 0 ? `&track=${pb.track}` : ""}`, + ) + .sort(), + ); + } + + await expect(stats.getByRole("link")).toHaveCount(2); + await expect(stats.getByRole("button")).toHaveCount(4); + await page.evaluate(() => { + (window as { progressStayed?: boolean }).progressStayed = true; + }); + await card("Bonuses completed").click(); + await expect(page).toHaveURL(/style=normal.*tracks=bonuses/); + await expect(times).toBeFocused(); + await expect(card("Bonuses completed")).toHaveAttribute( + "aria-pressed", + "true", + ); + await expectRuns(bonuses.personal_bests); + await expect(stats.getByRole("link", { name: /^Points/ })).toHaveAttribute( + "href", + "/leaderboards/points?track=bonuses", + ); + await card("Maps completed").click(); + await expect(card("Maps completed")).toHaveAttribute("aria-pressed", "true"); + await expectRuns(normal.personal_bests); + await card("Top 10s").click(); + await expect(page).toHaveURL(/show=top10/); + await expect(card("Top 10s")).toHaveAttribute("aria-pressed", "true"); + await expectRuns(top10); + await expect(times).toContainText(`All ${top10.length} top 10 finishes`); + await expect(card("Top 10s")).toContainText(String(top10.length)); + await times.getByRole("button", { name: /^Show/ }).click(); + await page + .getByRole("menuitemradio", { name: "All runs", exact: true }) + .click(); + await expectRuns(normal.personal_bests); + await card("World records").click(); + await expect(page).toHaveURL(/tracks=any.*show=records/); + await expect(card("World records")).toHaveAttribute("aria-pressed", "true"); + await expectRuns(all.filter((pb) => pb.rank === 1)); + await card("Top 10s").click(); + await expectRuns(all.filter((pb) => pb.rank != null && pb.rank <= 10)); + await expect(page.getByRole("button", { name: /^Style / })).toContainText( + "Normal", + ); + expect( + await page.evaluate( + () => (window as { progressStayed?: boolean }).progressStayed, + ), + ).toBe(true); + await page.getByRole("button", { name: /^Style / }).click(); + await page + .getByRole("menuitemradio", { name: "Autosync", exact: true }) + .click(); + await card("Bonuses completed").click(); + await expect(times).toContainText( + "No Autosync personal bests on bonuses yet.", + ); +}); + test("profile containers fit desktop and narrow phones", async ({ page }) => { await page.goto("/players/76561199900000002"); await expect(page.getByRole("heading", { level: 1 })).toBeVisible(); diff --git a/web/src/features/players/PlayerStyles.module.css b/web/src/features/players/PlayerStyles.module.css index 4628032..c2b5a5b 100644 --- a/web/src/features/players/PlayerStyles.module.css +++ b/web/src/features/players/PlayerStyles.module.css @@ -1,17 +1,97 @@ .stat { + isolation: isolate; background-image: radial-gradient( ellipse at 100% 0%, color-mix(in srgb, var(--stat-color) 12%, transparent), transparent 70% ); + transition: + border-color var(--duration-base) var(--ease-out), + box-shadow var(--duration-base) var(--ease-out), + transform var(--duration-base) var(--ease-out); +} + +.stat::before { + content: ""; + position: absolute; + z-index: -1; + inset: 0; + pointer-events: none; + background-image: inherit; + opacity: 0; + transition: opacity var(--duration-base) var(--ease-out); +} + +.stat[aria-pressed="true"] { + border-color: color-mix(in srgb, var(--stat-color) 45%, var(--color-border)); + background-color: color-mix( + in srgb, + var(--stat-color) 6%, + var(--color-surface) + ); +} + +.stat:focus-visible { + outline-color: var(--stat-color); } .icon { color: var(--stat-color); background-color: color-mix(in srgb, var(--stat-color) 20%, transparent); box-shadow: 0 0 20px color-mix(in srgb, var(--stat-color) 12%, transparent); + transition: + background-color var(--duration-base) var(--ease-out), + box-shadow var(--duration-base) var(--ease-out), + transform var(--duration-base) var(--ease-out); +} + +.value { + transition: color var(--duration-base) var(--ease-out); } .progress { background-color: var(--stat-color); } + +@media (hover: hover) { + .stat:is(:hover, :focus-visible) { + border-color: color-mix( + in srgb, + var(--stat-color) 45%, + var(--color-border) + ); + box-shadow: 0 4px 20px + color-mix(in srgb, var(--stat-color) 10%, transparent); + transform: translateY(-2px); + } + + .stat:is(:hover, :focus-visible)::before { + opacity: 1; + } + + .stat:is(:hover, :focus-visible) .icon { + background-color: color-mix(in srgb, var(--stat-color) 30%, transparent); + box-shadow: + 0 0 24px color-mix(in srgb, var(--stat-color) 25%, transparent), + inset 0 0 0 1px color-mix(in srgb, var(--stat-color) 25%, transparent); + transform: scale(1.06); + } + + .stat:is(:hover, :focus-visible) .value { + color: color-mix(in srgb, var(--stat-color) 65%, var(--color-text)); + } +} + +@media (prefers-reduced-motion: reduce) { + .stat, + .stat::before, + .icon, + .value { + transition: none; + } + + .stat:is(:hover, :focus-visible), + .stat:is(:hover, :focus-visible) .icon { + transform: none; + } +} diff --git a/web/src/features/players/PlayerStyles.tsx b/web/src/features/players/PlayerStyles.tsx index c4b9c29..dd32b32 100644 --- a/web/src/features/players/PlayerStyles.tsx +++ b/web/src/features/players/PlayerStyles.tsx @@ -9,6 +9,7 @@ import { type ReactNode, useCallback, useEffect, + useRef, useState, } from "react"; import { @@ -70,6 +71,7 @@ const numbers = new Intl.NumberFormat("en"); const ANY = "any"; type Tracks = "main" | "bonuses" | typeof ANY; +type Show = "all" | "records" | "top10"; export function PlayerStyles({ player, @@ -88,7 +90,8 @@ export function PlayerStyles({ bonusTotal?: number; }) { const params = useSearchParams(); - const choiceKey = params.toString(); + const times = useRef(null); + const choiceKey = `${player.steamid64}:${params.get("style") ?? ""}:${params.get("tracks") ?? ""}`; const [loaded, setLoaded] = useState<{ key: string; rows: Schemas["PersonalBest"][]; @@ -101,8 +104,11 @@ export function PlayerStyles({ const tracksParam = params.get("tracks"); const tracks: Tracks = tracksParam === "bonuses" || tracksParam === ANY ? tracksParam : "main"; - // World records are 2.0 placements, so showing them alone sets aside the pre-2.0 views. - const records = params.get("show") === "records"; + // Placements are 2.0's, so filtering by them sets aside the pre-2.0 views. + const showParam = params.get("show"); + const show: Show = + showParam === "records" || showParam === "top10" ? showParam : "all"; + const records = show === "records"; // The same choices on every profile, as on map pages: any style, every ranked style, then any the ruleset no // longer ranks that the player has times in. Styles without times are dimmed. const retired = player.styles @@ -122,7 +128,10 @@ export function PlayerStyles({ // The cards' numbers: one style's, or across every style. const counts = anyStyle ? player.all_styles : current; const withViews = - hasLegacy && styleKey === LEGACY_STYLE && tracks === "main" && !records; + hasLegacy && + styleKey === LEGACY_STYLE && + tracks === "main" && + show === "all"; // 2.0 first (lead, 2026-10-26); a player with no 2.0 runs in the style opens on their pre-2.0 runs. const view: View = withViews ? viewFrom(params.get("view"), current ? "current" : "legacy") @@ -132,10 +141,6 @@ export function PlayerStyles({ const shownTotal = tracks === "main" ? maps : tracks === "bonuses" ? bonuses : maps + bonuses; const styleName = anyStyle ? "" : `${styleNames[styleKey] ?? styleKey} `; - // The leaderboards and the map list are per style and kind of track; "any" opens their defaults. - const boardStyle = - anyStyle || styleKey === styleOrder[0] ? {} : { style: styleKey }; - const ranked = anyStyle ? styleKeys .map(summary) @@ -151,7 +156,7 @@ export function PlayerStyles({ const historyName = styleNames[historyStyle] ?? historyStyle; const rows = loaded?.key === choiceKey ? loaded.rows : undefined; const completeFirst = - tracks === "main" && !records && current && !current.next_cursor + tracks === "main" && current && !current.next_cursor ? current.personal_bests : undefined; const top10 = @@ -173,20 +178,32 @@ export function PlayerStyles({ style?: string; tracks?: Tracks; view?: View; - records?: boolean; + show?: Show; }) { const url = new URL(window.location.href); url.searchParams.set("style", choice.style ?? styleKey ?? LEGACY_STYLE); const nextTracks = choice.tracks ?? tracks; if (nextTracks === "main") url.searchParams.delete("tracks"); else url.searchParams.set("tracks", nextTracks); - if (choice.records ?? records) url.searchParams.set("show", "records"); + const nextShow = choice.show ?? show; + if (nextShow !== "all") url.searchParams.set("show", nextShow); else url.searchParams.delete("show"); if (choice.view) url.searchParams.set("view", choice.view); else url.searchParams.delete("view"); window.history.replaceState(null, "", url); } + function showTimes(nextShow: Show, nextTracks: Tracks = tracks) { + choose({ show: nextShow, tracks: nextTracks, view: "current" }); + times.current?.focus({ preventScroll: true }); + times.current?.scrollIntoView({ + behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches + ? "auto" + : "smooth", + block: "start", + }); + } + return ( <>
- records - ? choose({ - style: styleKeys.find(hasTimes) ?? styleKeys[0], - tracks: "main", - records: false, - }) - : choose({ style: ANY, tracks: ANY, records: true }) - : undefined - } + onClick={() => showTimes(records ? "all" : "records", ANY)} > World records @@ -226,7 +232,11 @@ export function PlayerStyles({ - + showTimes(show === "top10" ? "all" : "top10")} + > Top 10s @@ -235,7 +245,7 @@ export function PlayerStyles({ {top10 === undefined ? "—" : numbers.format(top10)} - + Points @@ -246,11 +256,8 @@ export function PlayerStyles({ showTimes("all", "main")} > Maps completed @@ -277,7 +284,11 @@ export function PlayerStyles({ )} - + showTimes("all", "bonuses")} + > Bonuses completed @@ -318,7 +329,12 @@ export function PlayerStyles({ {details} {/* The choices sit with the list they narrow, under the overview. */} -
+
Show} options={[ { value: "all", label: "All runs" }, @@ -344,9 +360,14 @@ export function PlayerStyles({ label: "World records", quiet: !counts?.world_records, }, + { value: "top10", label: "Top 10s", quiet: top10 === 0 }, ]} - value={records ? "records" : "all"} - onChange={(value) => choose({ records: value === "records" })} + value={show} + onChange={(value) => + choose({ + show: value === "records" || value === "top10" ? value : "all", + }) + } /> styleNames[key] ?? key} tracks={tracks === ANY ? undefined : tracks} view={view} records={records} + top10Only={show === "top10"} first={ view === "current" && tracks === "main" && current && !records ? { @@ -388,13 +410,13 @@ export function PlayerStyles({ // The world record count covers main tracks and bonuses together, so it can't total one of them; across // styles the counts are of maps, not of each style's personal best on them. total={ - view === "current" && !records && !anyStyle + view === "current" && show === "all" && !anyStyle ? shownTotal : undefined } /> )} -
+
); } @@ -439,12 +461,7 @@ function StatLink({ ); const style = { "--stat-color": color } as CSSProperties; // The panel clips its corners, so the focus ring is drawn inside the cell. - const clickable = classNames( - classes, - "hover:bg-text/4 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", - ); + const clickable = classNames(classes, "focus-visible:-outline-offset-2"); if (href) { return ( @@ -472,10 +489,15 @@ function StatLink({ ); } -/** A standing cell's number, accented on hover as at home. */ +/** A standing cell's number, accented in the card's color on hover. */ function StatValue({ children }: { children: ReactNode }) { return ( - + {children} ); @@ -512,6 +534,7 @@ function PersonalBests({ tracks, view, records, + top10Only, first, total, tierCount, @@ -526,13 +549,14 @@ function PersonalBests({ view: View; /** World records alone. */ records: boolean; + top10Only: boolean; /** The first page when it came with the profile; left out, it's loaded here. */ first?: Pick; /** How many there are, when known up front (2.0's counts); the other views count what they've shown. */ total?: number; /** Tiers in force, for the badges; undefined until the community sets tiers. */ tierCount?: number; - onLoaded: (rows: Schemas["PersonalBest"][]) => void; + onLoaded?: (rows: Schemas["PersonalBest"][]) => void; }) { // The API's own order: by map in one style, newest first across styles. const apiOrder: PbSort = style @@ -648,7 +672,7 @@ function PersonalBests({ useEffect(() => { if (personalBests && !cursor && !loading && !failed) - onLoaded(personalBests); + onLoaded?.(personalBests); }, [personalBests, cursor, loading, failed, onLoaded]); if (!personalBests) { @@ -663,12 +687,15 @@ function PersonalBests({

); } - const count = total ?? personalBests.length; + const matching = top10Only + ? personalBests.filter((pb) => pb.rank != null && pb.rank <= 10) + : personalBests; + const count = top10Only ? matching.length : (total ?? personalBests.length); // World records count bonuses with main tracks, so one kind of track can have none while the count doesn't. - if (personalBests.length === 0) { + if (matching.length === 0) { return (

- None + {top10Only ? "No top 10 finishes" : "None"} {tracks === "main" ? " on main tracks" : tracks === "bonuses" @@ -695,8 +722,8 @@ function PersonalBests({ : ("ascending" as const) : undefined; const rows = sameSort(sort, apiOrder) - ? personalBests - : sortedPbs(personalBests, sort, styleName); + ? matching + : sortedPbs(matching, sort, styleName); return (

@@ -855,19 +882,23 @@ function PersonalBests({
- {records - ? !cursor - ? count === 1 - ? "1 world record" - : `All ${count} world records` - : `${personalBests.length} world records so far` - : !cursor - ? count === 1 - ? "1 personal best" - : `All ${count} personal bests` - : total != null - ? `${personalBests.length} of ${total} personal bests` - : `${personalBests.length} personal bests so far`} + {top10Only + ? count === 1 + ? "1 top 10 finish" + : `All ${count} top 10 finishes` + : records + ? !cursor + ? count === 1 + ? "1 world record" + : `All ${count} world records` + : `${personalBests.length} world records so far` + : !cursor + ? count === 1 + ? "1 personal best" + : `All ${count} personal bests` + : total != null + ? `${personalBests.length} of ${total} personal bests` + : `${personalBests.length} personal bests so far`} {failed && (