diff --git a/api/.sqlx/query-0bfbe0266373668248628f241c61ed7472c84e03eb8177379011350cb79c84e8.json b/api/.sqlx/query-02235b882665d8454409c6721c6e7a34ffa7328ea8650f68b3ed0bad729c1e34.json similarity index 71% rename from api/.sqlx/query-0bfbe0266373668248628f241c61ed7472c84e03eb8177379011350cb79c84e8.json rename to api/.sqlx/query-02235b882665d8454409c6721c6e7a34ffa7328ea8650f68b3ed0bad729c1e34.json index 453b1f7..988b044 100644 --- a/api/.sqlx/query-0bfbe0266373668248628f241c61ed7472c84e03eb8177379011350cb79c84e8.json +++ b/api/.sqlx/query-02235b882665d8454409c6721c6e7a34ffa7328ea8650f68b3ed0bad729c1e34.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n WITH listed AS (\n SELECT r.id, r.map_id, r.style, r.track, r.player_steamid64, r.time, r.finished_at, tier.tier\n FROM runs r\n LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track\n ORDER BY assigned_at DESC LIMIT 1) tier ON $7\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n AND ($5::timestamptz IS NULL OR (r.finished_at, r.id) < ($5, $6::bigint))\n ORDER BY r.finished_at DESC, r.id DESC\n LIMIT $8\n )\n SELECT l.id, l.style, l.track, l.time, l.finished_at, l.tier AS \"tier?\", prior.best AS \"best?\",\n m.name AS map, place.placement AS \"placement?\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code\n FROM listed l\n CROSS JOIN LATERAL (\n SELECT min(e.time) AS best FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n ) prior\n JOIN maps m ON m.id = l.map_id\n JOIN players p ON p.steamid64 = l.player_steamid64\n LEFT JOIN LATERAL (\n SELECT 1 + count(*) AS placement FROM (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 <> l.player_steamid64\n GROUP BY e.player_steamid64\n HAVING min(e.time) < l.time\n ) faster\n ) place ON NOT EXISTS (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 = l.player_steamid64 AND e.time <= l.time\n )\n ORDER BY l.finished_at DESC, l.id DESC\n ", + "query": "\n WITH listed AS (\n SELECT r.id, r.map_id, r.style, r.track, r.player_steamid64, r.time, r.finished_at, tier.tier\n FROM runs r\n LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track\n ORDER BY assigned_at DESC LIMIT 1) tier ON $7\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n AND ($5::timestamptz IS NULL OR (r.finished_at, r.id) < ($5, $6::bigint))\n ORDER BY r.finished_at DESC, r.id DESC\n LIMIT $8 OFFSET $9\n )\n SELECT l.id, l.style, l.track, l.time, l.finished_at, l.tier AS \"tier?\", prior.best AS \"best?\",\n m.name AS map, place.placement AS \"placement?\",\n p.steamid64::text AS \"steamid64!\", p.name, p.avatar_url, p.country_code\n FROM listed l\n CROSS JOIN LATERAL (\n SELECT min(e.time) AS best FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n ) prior\n JOIN maps m ON m.id = l.map_id\n JOIN players p ON p.steamid64 = l.player_steamid64\n LEFT JOIN LATERAL (\n SELECT 1 + count(*) AS placement FROM (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 <> l.player_steamid64\n GROUP BY e.player_steamid64\n HAVING min(e.time) < l.time\n ) faster\n ) place ON NOT EXISTS (\n SELECT 1 FROM runs e\n WHERE e.map_id = l.map_id AND e.style = l.style AND e.track = l.track\n AND e.invalidated_at IS NULL AND (e.finished_at, e.id) < (l.finished_at, l.id)\n AND e.player_steamid64 = l.player_steamid64 AND e.time <= l.time\n )\n ORDER BY l.finished_at DESC, l.id DESC\n ", "describe": { "columns": [ { @@ -141,6 +141,7 @@ "Timestamptz", "Int8", "Bool", + "Int8", "Int8" ] }, @@ -160,5 +161,5 @@ true ] }, - "hash": "0bfbe0266373668248628f241c61ed7472c84e03eb8177379011350cb79c84e8" + "hash": "02235b882665d8454409c6721c6e7a34ffa7328ea8650f68b3ed0bad729c1e34" } diff --git a/api/.sqlx/query-7fc6e231d7984b3b86529449e28e100d4f3e2c846b85cb200ac020301aa634db.json b/api/.sqlx/query-7fc6e231d7984b3b86529449e28e100d4f3e2c846b85cb200ac020301aa634db.json new file mode 100644 index 0000000..8f7ceab --- /dev/null +++ b/api/.sqlx/query-7fc6e231d7984b3b86529449e28e100d4f3e2c846b85cb200ac020301aa634db.json @@ -0,0 +1,27 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT count(*) AS \"total!\"\n FROM runs r\n LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track\n ORDER BY assigned_at DESC LIMIT 1) tier ON $5\n WHERE r.invalidated_at IS NULL\n AND (NOT $4 OR r.was_record)\n AND ($1::text IS NULL OR r.style = $1)\n AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0))\n AND ($3::smallint IS NULL OR tier.tier >= $3)\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "total!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int2", + "Bool", + "Bool" + ] + }, + "nullable": [ + null + ] + }, + "hash": "7fc6e231d7984b3b86529449e28e100d4f3e2c846b85cb200ac020301aa634db" +} diff --git a/api/crates/api/src/runs/recent.rs b/api/crates/api/src/runs/recent.rs index 1038a9f..901ae56 100644 --- a/api/crates/api/src/runs/recent.rs +++ b/api/crates/api/src/runs/recent.rs @@ -33,6 +33,8 @@ pub struct RecentRunsQuery { records: Option, /// 1 to 100. Default 50. limit: Option, + /// Runs to skip, for going straight to a page. Default 0. Counted after `cursor` when both are given. + offset: Option, /// Continue after this point: a `next_cursor` from an earlier page with the same filters. cursor: Option, } @@ -52,6 +54,8 @@ pub struct RecentRuns { pub runs: Vec, /// Pass as `cursor` for the runs before these. None at the end. pub next_cursor: Option, + /// How many runs match the filters, across all pages. + pub total: i64, /// Number of tiers in force; None while the community hasn't set tiers, and runs then have no tier. pub tier_count: Option, } @@ -88,7 +92,7 @@ pub struct RecentRun { params(RecentRunsQuery), responses( (status = OK, body = RecentRuns), - (status = UNPROCESSABLE_ENTITY, description = "Not a valid tier, limit or cursor", body = ErrorBody), + (status = UNPROCESSABLE_ENTITY, description = "Not a valid tier, limit, offset or cursor", body = ErrorBody), ), )] pub async fn recent_runs( @@ -96,7 +100,8 @@ pub async fn recent_runs( Query(query): Query, ) -> Result, ApiError> { let limit = query.limit.unwrap_or(DEFAULT_LIMIT); - check_page(limit, 0, MAX_LIMIT).map_err(ApiError::Invalid)?; + let offset = query.offset.unwrap_or(0); + check_page(limit, offset, MAX_LIMIT).map_err(ApiError::Invalid)?; if query.min_tier.is_some_and(|tier| tier < 1) { return Err(ApiError::Invalid("min_tier must be 1 or more".to_owned())); } @@ -110,11 +115,16 @@ pub async fn recent_runs( return Ok(Json(RecentRuns { runs: Vec::new(), next_cursor: None, + total: 0, tier_count, })); } - let mut runs = page(&state.db, &query, after, limit + 1, tier_count.is_some()).await?; + let tiers_in_force = tier_count.is_some(); + let (mut runs, total) = tokio::try_join!( + page(&state.db, &query, after, limit + 1, offset, tiers_in_force), + count(&state.db, &query, tiers_in_force), + )?; let limit = usize::try_from(limit).expect("checked to be positive"); let next_cursor = (runs.len() > limit).then(|| { runs.truncate(limit); @@ -123,6 +133,7 @@ pub async fn recent_runs( Ok(Json(RecentRuns { runs, next_cursor: next_cursor.flatten(), + total, tier_count, })) } @@ -140,17 +151,50 @@ async fn position(db: &PgPool, cursor: &str) -> Result { Ok((finished_at, run_id)) } +fn track_key(query: &RecentRunsQuery) -> Option<&'static str> { + query.track.map(|track| match track { + TrackKind::Main => "main", + TrackKind::Bonus => "bonus", + }) +} + +/// Every run the filters match, ignoring `cursor`, `offset` and `limit`. The same conditions as `page`'s. +async fn count( + db: &PgPool, + query: &RecentRunsQuery, + tiers_in_force: bool, +) -> Result { + sqlx::query_scalar!( + r#" + SELECT count(*) AS "total!" + FROM runs r + LEFT JOIN LATERAL (SELECT tier FROM map_tiers WHERE map_id = r.map_id AND track = r.track + ORDER BY assigned_at DESC LIMIT 1) tier ON $5 + WHERE r.invalidated_at IS NULL + AND (NOT $4 OR r.was_record) + AND ($1::text IS NULL OR r.style = $1) + AND ($2::text IS NULL OR ($2 = 'main') = (r.track = 0)) + AND ($3::smallint IS NULL OR tier.tier >= $3) + "#, + query.style, + track_key(query), + query.min_tier, + query.records.unwrap_or(false), + tiers_in_force, + ) + .fetch_one(db) + .await +} + async fn page( db: &PgPool, query: &RecentRunsQuery, after: Option, limit: i64, + offset: i64, tiers_in_force: bool, ) -> Result, sqlx::Error> { - let track = query.track.map(|track| match track { - TrackKind::Main => "main", - TrackKind::Bonus => "bonus", - }); + let track = track_key(query); // "Before" a run means earlier on its board in WR history's order: finish time, then ID. Records only // reads the stored `was_record` through its own index (`leaderboards/world_records.rs`). `prior`, the // board's best before the run, and placements are worked out for the page's runs alone, reading the @@ -169,7 +213,7 @@ async fn page( AND ($3::smallint IS NULL OR tier.tier >= $3) AND ($5::timestamptz IS NULL OR (r.finished_at, r.id) < ($5, $6::bigint)) ORDER BY r.finished_at DESC, r.id DESC - LIMIT $8 + LIMIT $8 OFFSET $9 ) SELECT l.id, l.style, l.track, l.time, l.finished_at, l.tier AS "tier?", prior.best AS "best?", m.name AS map, place.placement AS "placement?", @@ -206,7 +250,8 @@ async fn page( after.map(|(finished_at, _)| finished_at), after.map(|(_, run_id)| run_id), tiers_in_force, - limit + limit, + offset ) .fetch_all(db) .await?; @@ -360,6 +405,29 @@ mod tests { assert_eq!(test_client::get(&db, "/v1/runs?cursor=x").await.status, 422); assert_eq!(test_client::get(&db, "/v1/runs?limit=0").await.status, 422); + // An offset goes straight to a page, and the total counts the whole filtered list, not the page. + let third = list(&db, "?limit=2&offset=2").await; + assert_eq!( + third, + [ + row("ricochet", "bhop_badges", 0, 28.0, Some(1), true), + row("ricochet", "bhop_badges", 0, 33.0, Some(2), false), + ] + ); + let last: RecentRuns = test_client::get(&db, "/v1/runs?limit=2&offset=4") + .await + .json(); + assert_eq!((last.runs.len(), last.total), (1, 5)); + assert_eq!(last.next_cursor, None); + let main: RecentRuns = test_client::get(&db, "/v1/runs?track=main&limit=1") + .await + .json(); + assert_eq!(main.total, 4); + assert_eq!( + test_client::get(&db, "/v1/runs?offset=-1").await.status, + 422 + ); + // An invalidated record leaves the list, and the record it had beaten is the board's best again. let run_id: i64 = sqlx::query_scalar("SELECT id FROM runs WHERE server_run_id = 'c'") .fetch_one(&db) @@ -387,7 +455,8 @@ mod tests { ] { test_client::post(&db, "/v1/runs", Some(&key), &body).await; } - assert_eq!(list(&db, "?min_tier=1").await.len(), 0); + let none: RecentRuns = test_client::get(&db, "/v1/runs?min_tier=1").await.json(); + assert_eq!((none.runs.len(), none.total), (0, 0)); assert_eq!( test_client::get(&db, "/v1/runs?min_tier=0").await.status, 422 diff --git a/api/openapi.json b/api/openapi.json index 0edd3eb..659546f 100644 --- a/api/openapi.json +++ b/api/openapi.json @@ -2039,6 +2039,19 @@ "format": "int64" } }, + { + "name": "offset", + "in": "query", + "description": "Runs to skip, for going straight to a page. Default 0. Counted after `cursor` when both are given.", + "required": false, + "schema": { + "type": [ + "integer", + "null" + ], + "format": "int64" + } + }, { "name": "cursor", "in": "query", @@ -2063,7 +2076,7 @@ } }, "422": { - "description": "Not a valid tier, limit or cursor", + "description": "Not a valid tier, limit, offset or cursor", "content": { "application/json": { "schema": { @@ -8858,7 +8871,8 @@ "RecentRuns": { "type": "object", "required": [ - "runs" + "runs", + "total" ], "properties": { "next_cursor": { @@ -8882,6 +8896,11 @@ ], "format": "int32", "description": "Number of tiers in force; None while the community hasn't set tiers, and runs then have no tier." + }, + "total": { + "type": "integer", + "format": "int64", + "description": "How many runs match the filters, across all pages." } } }, diff --git a/docs/site-api.md b/docs/site-api.md index a5eeb91..6a0bec7 100644 --- a/docs/site-api.md +++ b/docs/site-api.md @@ -34,7 +34,7 @@ Players sign in with Steam (OpenID 2.0). These endpoints answer browsers with re - Stored, not computed per visit (lead, 2026-10-26): `personal_bests.points`, `standings` (per style, main and bonuses apart) and `legacy_standings`, recounted by `leaderboards/standings.rs` where they change: a track when a personal best or its tier changes there (a new WR moves all points); everything on a points or tiers policy, or at startup if the formula changed; legacy on bans, lifts, imports. One advisory lock serializes recounts. So are world records (`leaderboards/world_records.rs`): holders and `runs.was_record`, per board. ## Activity -- `GET /v1/runs?style=&track=main|bonus&min_tier=&records=&cursor=` (`runs/recent.rs`): valid runs newest first by `finished_at`, each with its board's tier, `placement` counted against the valid runs before it (null unless it beat the player's own best), `world_record` (as in WR history) and its `gap` to the record it faced. `min_tier` matches nothing until a tier count is published. +- `GET /v1/runs?style=&track=main|bonus&min_tier=&records=&cursor=&offset=` (`runs/recent.rs`, with `total`): valid runs newest first by `finished_at`, each with its board's tier, `placement` against the valid runs before it (null unless a personal best), `world_record` (as in WR history) and `gap` to the record it faced. `min_tier` matches nothing until a tier count is published. ## Daily totals - `GET /v1/daily-totals/players|runs?range=month|year|all` (`daily_totals.rs`, hourly): players with a time (incl. pre-2.0), 2.0 runs and WRs per UTC day. diff --git a/web/src/api/schema.ts b/web/src/api/schema.ts index efc166b..c0bc7c7 100644 --- a/web/src/api/schema.ts +++ b/web/src/api/schema.ts @@ -2657,6 +2657,11 @@ export interface components { * @description Number of tiers in force; None while the community hasn't set tiers, and runs then have no tier. */ tier_count?: number | null; + /** + * Format: int64 + * @description How many runs match the filters, across all pages. + */ + total: number; }; Record: { /** Format: date-time */ @@ -4688,6 +4693,8 @@ export interface operations { records?: boolean | null; /** @description 1 to 100. Default 50. */ limit?: number | null; + /** @description Runs to skip, for going straight to a page. Default 0. Counted after `cursor` when both are given. */ + offset?: number | null; /** @description Continue after this point: a `next_cursor` from an earlier page with the same filters. */ cursor?: string | null; }; @@ -4705,7 +4712,7 @@ export interface operations { "application/json": components["schemas"]["RecentRuns"]; }; }; - /** @description Not a valid tier, limit or cursor */ + /** @description Not a valid tier, limit, offset or cursor */ 422: { headers: { [name: string]: unknown; diff --git a/web/src/app/activity/page.tsx b/web/src/app/activity/page.tsx index 7de643e..df4720b 100644 --- a/web/src/app/activity/page.tsx +++ b/web/src/app/activity/page.tsx @@ -1,5 +1,5 @@ -// Activity page: runs and world records per day, then the latest runs, narrowed by style, track, lowest tier or -// world records only. +// Activity page: one board. Runs and world records per day, then the latest runs, narrowed by style, track, +// lowest tier or world records only. import type { Metadata } from "next"; import { RecentRuns } from "@/features/activity/RecentRuns"; import { DailyTotals } from "@/features/dailyTotals/DailyTotals"; @@ -12,19 +12,21 @@ export const metadata: Metadata = { export default function ActivityPage({ searchParams }: PageProps<"/activity">) { return ( - -

Activity

- - {searchParams.then(({ style, track, tier, show }) => ( - - ))} + +
+ + {searchParams.then(({ style, track, tier, show, page }) => ( + + ))} +
); } diff --git a/web/src/features/activity/RecentRunTable.tsx b/web/src/features/activity/RecentRunTable.tsx index 94358af..3edcd8f 100644 --- a/web/src/features/activity/RecentRunTable.tsx +++ b/web/src/features/activity/RecentRunTable.tsx @@ -1,23 +1,32 @@ "use client"; -// The latest runs as a table: who, which board, the time, and where it placed when it finished. "Show more" -// loads older runs a page at a time. -import { useState, type CSSProperties } from "react"; +// The latest runs as a table: who, which board, the time, and where it placed when it finished. Runs come a +// hundred at a time and are paged here, so turning a page is instant; the next hundred load in the background. +import { useSearchParams } from "next/navigation"; +import { + useCallback, + useEffect, + useRef, + useState, + type CSSProperties, + type FormEvent, + type MouseEvent, +} from "react"; import { api, type Schemas } from "@/api/client"; +import { ReplayLink } from "@/features/replays/ReplayLink"; import { RunLink } from "@/features/runs/RunLink"; import { + formatAge, formatGap, - formatSince, formatTime, trackName, } from "@/features/runs/time"; import { Avatar } from "@/ui/Avatar"; import { Badge } from "@/ui/Badge"; -import { Button } from "@/ui/Button"; -import { Card } from "@/ui/Card"; import { classNames } from "@/ui/classNames"; import { Flag } from "@/ui/Flag"; import { Link } from "@/ui/Link"; import { Medal } from "@/ui/Medal"; +import { Pager } from "@/ui/Pager"; import { Table, TableBody, @@ -28,183 +37,377 @@ import { } from "@/ui/Table"; import { TierBadge } from "@/ui/TierBadge"; -type Page = Schemas["RecentRuns"]; +type Run = Schemas["RecentRun"]; type Query = { style?: string; track?: "main" | "bonus"; min_tier?: number; records?: boolean; + /** Runs per request, a whole number of pages. */ + limit: number; }; +/** + * Runs loaded so far, by chunk: chunk `k` starts `k * limit` runs from the newest. With `total`, the API takes + * offsets and any chunk can load. Without it (an API before `total`), chunks load in order from `cursor`. + */ +export interface RunChunks { + chunks: Record; + total: number | null; + cursor: string | null; + tierCount: number | null; +} + export function RecentRunTable({ first, query, + address, + pageSize, styleNames, showStyle, }: { - first: Page; - /** The filters `first` was loaded with, for loading the pages after it. */ + /** The chunk holding the page in the address, or every chunk up to it. */ + first: RunChunks; + /** The filters `first` was loaded with, for loading the rest. */ query: Query; + /** The page's address with these filters, which the page number is added to. */ + address: string; + pageSize: number; styleNames: Record; /** With every style shown, each run names its own. */ showStyle: boolean; }) { - const [runs, setRuns] = useState(first.runs); - const [cursor, setCursor] = useState(first.next_cursor); - const [loading, setLoading] = useState(false); + const [loaded, setLoaded] = useState(first); const [failed, setFailed] = useState(false); - const tierCount = first.tier_count; - - async function showMore(after: string) { - setLoading(true); - setFailed(false); - const loaded = await api - .GET("/v1/runs", { params: { query: { ...query, cursor: after } } }) - .then((result) => result.data) - .catch(() => undefined); - setLoading(false); - if (!loaded) { - setFailed(true); - return; + const [waiting, setWaiting] = useState(false); + const [turned, setTurned] = useState(false); + // The latest chunks for the loops below, which outlive the render that started them. + const latest = useRef(first); + const inFlight = useRef(new Map>()); + const turns = useRef(0); + const board = useRef(null); + const rows = useRef(null); + // Held at the first page's height, so a short last page doesn't pull the page controls up. + const [minHeight, setMinHeight] = useState(); + const tierCount = first.tierCount; + const chunk = query.limit; + const pagesPerChunk = chunk / pageSize; + const chunkOf = (p: number) => Math.floor((p - 1) / pagesPerChunk); + + // No `page` means page 1, never the page the table first opened on. + const asked = Math.max( + 1, + Math.floor(Number(useSearchParams().get("page") ?? 1)) || 1, + ); + const more = loaded.total == null && loaded.cursor != null; + const pageCount = pagesIn(loaded, pageSize); + // Counted by the API, or once the last chunk has loaded without it. + const total = loaded.total ?? (loaded.cursor == null ? runsIn(loaded) : null); + const page = Math.min(asked, pageCount); + const shown = + loaded.chunks[chunkOf(page)]?.slice( + ((page - 1) % pagesPerChunk) * pageSize, + (((page - 1) % pagesPerChunk) + 1) * pageSize, + ) ?? []; + + const pageHref = useCallback( + (p: number) => + p > 1 + ? `${address}${address.includes("?") ? "&" : "?"}page=${p}` + : address, + [address], + ); + + /** Loads chunk `k`, once however many ask; false when it can't be loaded yet or failed. */ + const load = useCallback( + (k: number): Promise => { + const pending = inFlight.current.get(k); + if (pending) return pending; + const { chunks, total, cursor } = latest.current; + const byOffset = total != null; + if (!byOffset && (k !== Object.keys(chunks).length || !cursor)) + return Promise.resolve(false); + const request = api + .GET("/v1/runs", { + params: { + query: byOffset + ? { ...query, offset: k * query.limit } + : { ...query, cursor: cursor ?? undefined }, + }, + }) + .then((result) => result.data) + .catch(() => undefined) + .then((next) => { + inFlight.current.delete(k); + setFailed(!next); + if (!next) return false; + latest.current = { + ...latest.current, + chunks: { ...latest.current.chunks, [k]: next.runs }, + // The count moves as runs come in, so the newest answer wins. + total: byOffset ? next.total : null, + cursor: byOffset ? null : (next.next_cursor ?? null), + }; + setLoaded(latest.current); + return true; + }); + inFlight.current.set(k, request); + return request; + }, + [query], + ); + + /** Loads chunk `k`, walking the chunks before it first on an API without offsets. */ + const ensure = useCallback( + async (k: number): Promise => { + while (!latest.current.chunks[k]) { + const { chunks, total } = latest.current; + if (!(await load(total != null ? k : Object.keys(chunks).length))) + return false; + } + return true; + }, + [load], + ); + + // Loads the page asked for if it isn't yet, as after going back to a far page, and the chunks either side of + // it, so Next and Previous never wait. + const askedChunk = chunkOf(asked); + useEffect(() => { + if (failed) return; + void ensure(askedChunk).then((ok) => { + if (!ok) return; + const { total } = latest.current; + if (total == null || (askedChunk + 1) * chunk < total) + void ensure(askedChunk + 1); + if (askedChunk > 0) void ensure(askedChunk - 1); + }); + }, [askedChunk, failed, ensure, chunk]); + + // Past the last run, the address is corrected to the last page rather than showing one page and naming another. + useEffect(() => { + if (!more && asked > pageCount) + window.history.replaceState(null, "", pageHref(pageCount)); + }, [more, asked, pageCount, pageHref]); + + async function go(target: number) { + const turn = ++turns.current; + const known = latest.current.total; + const wanted = + known != null + ? Math.min(target, pagesIn(latest.current, pageSize)) + : target; + if (!latest.current.chunks[chunkOf(wanted)]) { + setWaiting(true); + // A typed page past what's loaded walks forward to it, or to the last page if the runs end first. + await ensure(chunkOf(wanted)); } - setRuns((shown) => [...shown, ...loaded.runs]); - setCursor(loaded.next_cursor); + // A later click wins over one still loading. + if (turn !== turns.current) return; + setWaiting(false); + setTurned(true); + const next = pageHref(Math.min(wanted, pagesIn(latest.current, pageSize))); + setMinHeight((held) => held ?? rows.current?.offsetHeight); + if (next !== window.location.pathname + window.location.search) + window.history.pushState(null, "", next); + // Keep the table's top in view when a page is turned from the bottom of a long page. + const top = board.current?.getBoundingClientRect().top ?? 0; + if (top < 0) board.current?.scrollIntoView({ block: "start" }); + } + + // The pager's links and box work without this; here they turn the page without asking the server. + 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 and Form navigate even when the event is already prevented. + event.preventDefault(); + event.stopPropagation(); + void go(Number(new URL(link.href).searchParams.get("page") ?? 1)); } - if (runs.length === 0) { + function onPagerSubmit(event: FormEvent) { + event.preventDefault(); + event.stopPropagation(); + const form = event.target as HTMLFormElement; + const typed = Math.floor(Number(new FormData(form).get("page"))); + form.reset(); + if (typed >= 1) void go(typed); + } + + if (loaded.total === 0 || (pageCount === 1 && !more && shown.length === 0)) { return ( - +

{query.records ? "No world records match these choices." : "No runs match these choices."} - +

); } return ( -
- - - - When - Player - Map - Time - - Place - - - - - {runs.map((run, index) => ( - - - {/* Counted from now, which differs between the server's render and the browser's. */} - - - - - - - {run.player.name} - - - - - - - {run.tier != null && tierCount != null && ( - - )} - - {run.map} - - {(run.track > 0 || showStyle) && ( - - {[ - run.track > 0 && trackName(run.track), - showStyle && (styleNames[run.style] ?? run.style), - ] - .filter(Boolean) - .join(" · ")} - - )} - - - - {/* Against the record when the run finished: what a new WR took off, or how far behind it was. */} - {run.gap != null && ( - 0 - ? "text-danger" - : "text-text-subtle", +
+
+
+ + + Player + Map + + Time + + {/* Narrow padding keeps the play button close to the time and the place. */} + + Replay + + + Place + + + + + {shown.map((run, row) => ( + + + + + + {run.player.name} + + + + + + + {run.tier != null && tierCount != null && ( + + )} + + {run.map} + + {(run.track > 0 || showStyle) && ( + + {[ + run.track > 0 && trackName(run.track), + showStyle && (styleNames[run.style] ?? run.style), + ] + .filter(Boolean) + .join(" · ")} + )} - > - {run.gap < 0 - ? `−${formatTime(-run.gap)}` - : formatGap(run.gap)} - )} - - {formatTime(run.time)} - - - - {run.world_record ? ( - WR - ) : run.placement != null ? ( - - + + + + + + {formatTime(run.time)} + + {/* Against the record when the run finished: what a new WR took off, or how far behind it was. */} + {run.gap != null && ( + 0 + ? "text-danger" + : "text-text-subtle", + )} + > + {run.gap < 0 + ? `(−${formatTime(-run.gap)})` + : `(${formatGap(run.gap)})`} + + )} + + {/* Counted from now, which differs between the server's render and the browser's. */} + - ) : ( - – - )} - - - ))} - -
-
- {failed && ( - - More couldn't be loaded. Try again. - - )} - {cursor && ( - - )} + + + + + + {run.world_record ? ( + WR + ) : run.placement != null ? ( + + + + ) : ( + – + )} + + + ))} + +
+ {(pageCount > 1 || more) && ( +
+ +
+ )} + {failed && ( +

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

+ )}
); } @@ -215,3 +418,14 @@ function mapHref(run: Schemas["RecentRun"]): string { if (run.track > 0) search.set("track", String(run.track)); return `/maps/${run.map}?${search}`; } + +function runsIn(loaded: RunChunks): number { + return Object.values(loaded.chunks).reduce( + (sum, runs) => sum + runs.length, + 0, + ); +} + +function pagesIn(loaded: RunChunks, pageSize: number): number { + return Math.max(1, Math.ceil((loaded.total ?? runsIn(loaded)) / pageSize)); +} diff --git a/web/src/features/activity/RecentRuns.tsx b/web/src/features/activity/RecentRuns.tsx index 87ba140..7673d9c 100644 --- a/web/src/features/activity/RecentRuns.tsx +++ b/web/src/features/activity/RecentRuns.tsx @@ -3,7 +3,7 @@ import { api } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; import { ChoiceBar } from "@/ui/ChoiceBar"; import { ChoiceMenu } from "@/ui/ChoiceMenu"; -import { RecentRunTable } from "./RecentRunTable"; +import { RecentRunTable, type RunChunks } from "./RecentRunTable"; const tracks = [ { key: "all", label: "All" }, @@ -19,8 +19,22 @@ export interface RecentRunsParams { tier?: string; /** "records": world records only. */ show?: string; + page?: string; } +const PAGE_SIZE = 15; +/** Runs per request, six pages: ninety cost the API about what fifteen do, so most pages turn without a request. */ +const CHUNK = 90; +/** How far an address may walk an API without offsets before giving up, at one request per chunk. */ +const MAX_CHUNKS = 20; + +type RunsQuery = { + style?: string; + track?: "main" | "bonus"; + min_tier?: number; + records?: boolean; +}; + interface Filters { style?: string; track: Track; @@ -29,24 +43,31 @@ interface Filters { } export async function RecentRuns({ params }: { params: RecentRunsParams }) { - const styles = await currentStyles(); - const filters: Filters = { - style: styles.keys.find((key) => key === params.style), - track: tracks.find((t) => t.key === params.track)?.key ?? "all", - tier: Math.floor(Number(params.tier)) || undefined, - records: params.show === "records", - }; - const query = { - style: filters.style, - track: filters.track === "all" ? undefined : filters.track, - min_tier: filters.tier, - records: filters.records || undefined, - }; - const result = await api - .GET("/v1/runs", { params: { query } }) - .catch(() => undefined); - const first = result?.data; - const tierCount = first?.tier_count ?? undefined; + const track = tracks.find((t) => t.key === params.track)?.key ?? "all"; + const tier = Math.floor(Number(params.tier)) || undefined; + const records = params.show === "records"; + const page = Math.max(1, Math.floor(Number(params.page)) || 1); + const queryFor = (style: string | undefined): RunsQuery => ({ + style, + track: track === "all" ? undefined : track, + min_tier: tier, + records: records || undefined, + }); + + // The runs don't wait for the ruleset: the style in the address is almost always one it ranks, and only a + // stale one costs a second request. + const [styles, guessed] = await Promise.all([ + currentStyles(), + loadRuns(queryFor(params.style || undefined), page), + ]); + const style = styles.keys.find((key) => key === params.style); + const query = queryFor(style); + const first = + style === (params.style || undefined) + ? guessed + : await loadRuns(query, page); + const filters: Filters = { style, track, tier, records }; + const tierCount = first?.tierCount ?? undefined; // Only what differs from the defaults goes in the address, so the plain page stays /activity. const href = (choice: Partial) => { @@ -61,68 +82,78 @@ export async function RecentRuns({ params }: { params: RecentRunsParams }) { }; return ( -
- - - {styles.keys.length > 1 && ( +
+
+ ({ - value: key, - label: styles.name(key), - href: href({ style: key }), - })), + { + value: "all", + label: "All runs", + href: href({ records: false }), + }, + { + value: "records", + label: "World records", + href: href({ records: true }), + }, ]} - value={filters.style ?? ""} + value={filters.records ? "records" : "all"} /> - )} - ({ - value: t.key, - label: t.label, - href: href({ track: t.key }), - }))} - value={filters.track} - /> - {/* Tiers are the community's to set; until a tier count is published there's nothing to filter by. */} - {tierCount != null && ( + {styles.keys.length > 1 && ( + ({ + value: key, + label: styles.name(key), + href: href({ style: key }), + })), + ]} + value={filters.style ?? ""} + /> + )} ({ - value: String(i + 1), - label: `Tier ${i + 1}`, - href: href({ tier: i + 1 }), - })), - ]} - value={filters.tier ? String(filters.tier) : ""} + label="Track" + options={tracks.map((t) => ({ + value: t.key, + label: t.label, + href: href({ track: t.key }), + }))} + value={filters.track} /> - )} - + {/* Tiers are the community's to set; until a tier count is published there's nothing to filter by. */} + {tierCount != null && ( + ({ + value: String(i + 1), + label: `Tier ${i + 1}`, + href: href({ tier: i + 1 }), + })), + ]} + value={filters.tier ? String(filters.tier) : ""} + /> + )} + +
{!first ? ( -

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

+

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

) : ( // Keyed by the filters, so a new choice starts again from the newest runs and they all fade in. [key, styles.name(key)]), )} @@ -132,3 +163,50 @@ export async function RecentRuns({ params }: { params: RecentRunsParams }) {
); } + +/** The chunk holding `page`; undefined when the first request fails. */ +async function loadRuns( + query: RunsQuery, + page: number, +): Promise { + const get = (from: { offset?: number; cursor?: string }) => + api + .GET("/v1/runs", { + params: { query: { ...query, limit: CHUNK, ...from } }, + }) + .then((result) => result.data) + .catch(() => undefined); + const wanted = Math.floor(((page - 1) * PAGE_SIZE) / CHUNK); + const first = await get({ offset: wanted * CHUNK }); + if (!first) return undefined; + const tierCount = first.tier_count ?? null; + + // An API that counts its runs honours the offset, so this is the page's own chunk. One past the end is asked + // again for the last chunk. + if (typeof first.total === "number") { + const last = Math.max(0, Math.ceil(first.total / CHUNK) - 1); + const page = wanted > last ? await get({ offset: last * CHUNK }) : first; + if (!page) return undefined; + return { + chunks: { [Math.min(wanted, last)]: page.runs }, + total: page.total, + cursor: null, + tierCount, + }; + } + + // One that doesn't (the beta before `total`) ignored the offset and sent the newest runs, so walk forward. + const chunks: Record = { 0: first.runs }; + let cursor = first.next_cursor ?? null; + for ( + let chunk = 1; + cursor && chunk <= wanted && chunk < MAX_CHUNKS; + chunk++ + ) { + const next = await get({ cursor }); + if (!next) break; + chunks[chunk] = next.runs; + cursor = next.next_cursor ?? null; + } + return { chunks, total: null, cursor, tierCount }; +} diff --git a/web/src/features/dailyTotals/DailyTotals.tsx b/web/src/features/dailyTotals/DailyTotals.tsx index 1321117..531bded 100644 --- a/web/src/features/dailyTotals/DailyTotals.tsx +++ b/web/src/features/dailyTotals/DailyTotals.tsx @@ -9,7 +9,17 @@ import { const ranges = ["month", "year", "all"] as const satisfies TotalsRange[]; -export async function DailyTotals({ kind }: { kind: DailyTotalsData["kind"] }) { +export async function DailyTotals({ + kind, + heading, + plain = false, +}: { + kind: DailyTotalsData["kind"]; + /** Sits in the chart's top row, so the page doesn't spend a line on its own title. */ + heading?: string; + /** Draws on the parent's surface instead of its own card. */ + plain?: boolean; +}) { const data: DailyTotalsData = kind === "players" ? { @@ -52,6 +62,8 @@ export async function DailyTotals({ kind }: { kind: DailyTotalsData["kind"] }) { ); } diff --git a/web/src/features/dailyTotals/DailyTotalsChart.tsx b/web/src/features/dailyTotals/DailyTotalsChart.tsx index ddc43bd..bde99b4 100644 --- a/web/src/features/dailyTotals/DailyTotalsChart.tsx +++ b/web/src/features/dailyTotals/DailyTotalsChart.tsx @@ -5,6 +5,7 @@ import { type ReactNode, useState } from "react"; import type { Schemas } from "@/api/client"; import { Card } from "@/ui/Card"; +import { classNames } from "@/ui/classNames"; import { LineChart } from "@/ui/LineChart"; import { Segmented } from "@/ui/Segmented"; @@ -52,9 +53,13 @@ interface Point { export function DailyTotalsChart({ data, initialRange, + heading, + plain = false, }: { data: DailyTotalsData; initialRange: TotalsRange; + heading?: string; + plain?: boolean; }) { const [range, setRange] = useState(initialRange); const [active, setActive] = useState(null); @@ -77,35 +82,93 @@ export function DailyTotalsChart({ const bucketDays = current?.bucket_days ?? 1; const rangeLabel = ranges.find((r) => r.value === range)?.label ?? ""; - return ( - -
- {shown && ( -

- {data.kind === "players" ? ( - - {shown.y === 1 ? "player" : "players"} with a recorded time - - ) : ( - <> - {/* Each number in its line's color, so the line reads as the legend. */} - - {shown.y === 1 ? "run" : "runs"} - - - - {shown.y2 === 1 ? "world record" : "world records"} - - - )} - - - {when(shown.day, bucketDays)} - -

+ const stats = shown && ( +

+ {data.kind === "players" ? ( + + {shown.y === 1 ? "player" : "players"} with a recorded time + + ) : ( + <> + {/* Each number in its line's color, so the line reads as the legend. */} + + {shown.y === 1 ? "run" : "runs"} + + + + {shown.y2 === 1 ? "world record" : "world records"} + + + )} + + + {when(shown.day, bucketDays)} + +

+ ); + + const plot = + points.length < 2 ? ( +

+ {current + ? "Not enough days yet to draw a chart." + : "This range couldn't be loaded."} +

+ ) : ( +
+ ({ + x: Date.parse(p.day), + y: p.y, + y2: p.y2, + }))} + active={active} + onActive={setActive} + formatValue={(value) => axis.format(Math.round(value))} + /> + {/* Indented by the value labels' width, so the dates sit under the plot's ends. */} +
+ {date.format(new Date(points[0]?.day ?? 0))} + {date.format(new Date(points.at(-1)?.day ?? 0))} +
+
+ ); + + const frame = ( + <> +
+ {heading ? ( +
+

{heading}

+ {stats} +
+ ) : ( + stats )}
- - {points.length < 2 ? ( -

- {current - ? "Not enough days yet to draw a chart." - : "This range couldn't be loaded."} -

- ) : ( -
- ({ - x: Date.parse(p.day), - y: p.y, - y2: p.y2, - }))} - active={active} - onActive={setActive} - formatValue={(value) => axis.format(Math.round(value))} - /> - {/* Indented by the value labels' width, so the dates sit under the plot's ends. */} -
- {date.format(new Date(points[0]?.day ?? 0))} - {date.format(new Date(points.at(-1)?.day ?? 0))} -
-
- )} - + {plot} + ); + + if (plain) return
{frame}
; + return {frame}; } function Stat({ diff --git a/web/src/features/maps/MapList.tsx b/web/src/features/maps/MapList.tsx index 2569051..a812560 100644 --- a/web/src/features/maps/MapList.tsx +++ b/web/src/features/maps/MapList.tsx @@ -348,6 +348,8 @@ export async function MapList({ params }: { params: MapListParams }) { href({ page: p })} /> diff --git a/web/src/features/replays/ReplayLink.tsx b/web/src/features/replays/ReplayLink.tsx new file mode 100644 index 0000000..2387596 --- /dev/null +++ b/web/src/features/replays/ReplayLink.tsx @@ -0,0 +1,33 @@ +"use client"; +// A play button for a run's replay. A click plays it in a dialog over the page; a new tab opens the run page. +import { Play } from "lucide-react"; +import type { MouseEvent } from "react"; +import { openRun } from "@/features/runs/runDialog"; +import { REPLAY_ANCHOR } from "./anchor"; + +export function ReplayLink({ runId }: { runId: number }) { + function onClick(event: MouseEvent) { + if ( + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey || + event.button !== 0 + ) { + return; + } + event.preventDefault(); + openRun(runId, { replay: true }); + } + return ( + + + + ); +} diff --git a/web/src/features/replays/ReplayPlayer.tsx b/web/src/features/replays/ReplayPlayer.tsx index e1ebbcb..e6b1741 100644 --- a/web/src/features/replays/ReplayPlayer.tsx +++ b/web/src/features/replays/ReplayPlayer.tsx @@ -70,17 +70,21 @@ type Prepared = { map: string; loading: ReturnType }; export function ReplayPlayer({ run, styleNames, + startNow = false, }: { run: Schemas["RunDetail"]; /** Ranked styles' names by key, for a compared run of another style. */ styleNames: Record; + /** Start without waiting for a press, as in the replay dialog. */ + startNow?: boolean; }) { const [pressedPhase, setPhase] = useState({ kind: "poster" }); - const autoStart = useSyncExternalStore( + const openedAtAnchor = useSyncExternalStore( subscribeToHash, openedAtReplay, () => false, ); + const autoStart = startNow || openedAtAnchor; const phase: Phase = pressedPhase.kind === "poster" && autoStart ? { kind: "loading" } diff --git a/web/src/features/runs/RunDialogHost.tsx b/web/src/features/runs/RunDialogHost.tsx index a8b0241..edf8d75 100644 --- a/web/src/features/runs/RunDialogHost.tsx +++ b/web/src/features/runs/RunDialogHost.tsx @@ -2,6 +2,7 @@ // The run dialog, over whichever page is open. It opens the moment a run link is clicked and loads the run // inside, so the page behind never reloads (lead, 2026-10-19). It shows what everyone sees; staff act on the // run on its own page. Pre-2.0 runs open in it too, with what the old site kept; they have no run page. +import dynamic from "next/dynamic"; import { useSearchParams } from "next/navigation"; import { useEffect, useState } from "react"; import { api, type Schemas } from "@/api/client"; @@ -12,7 +13,13 @@ import { Button, ButtonLink } from "@/ui/Button"; import { Dialog } from "@/ui/Dialog"; import { Tooltip } from "@/ui/Tooltip"; import { RunDetailList } from "./RunDetailList"; -import { closeRun, PRE_RUN_PARAM, RUN_PARAM } from "./runDialog"; +import { closeRun, PRE_RUN_PARAM, REPLAY_PARAM, RUN_PARAM } from "./runDialog"; + +// The viewer is large, so it loads only once a replay is opened, not with every page. +const ReplayPlayer = dynamic( + () => import("@/features/replays/ReplayPlayer").then((m) => m.ReplayPlayer), + { ssr: false }, +); type Run = | { legacy: false; run: Schemas["RunDetail"] } @@ -52,10 +59,12 @@ async function loadRun(id: string, legacy: boolean): Promise { export function RunDialogHost() { const params = useSearchParams(); const runId = params.get(RUN_PARAM); + const replayId = params.get(REPLAY_PARAM); const preRunId = params.get(PRE_RUN_PARAM); - const id = runId ?? preRunId; - const legacy = runId == null && preRunId != null; - const key = id && `${legacy ? "pre" : "run"}-${id}`; + const id = runId ?? replayId ?? preRunId; + const replay = runId == null && replayId != null; + const legacy = runId == null && replayId == null && preRunId != null; + const key = id && `${legacy ? "pre" : replay ? "replay" : "run"}-${id}`; const [loaded, setLoaded] = useState(); const [names, setNames] = useState>(new Map()); @@ -82,6 +91,37 @@ export function RunDialogHost() { const shown = loaded?.key === key ? loaded : undefined; const run = shown && "run" in shown ? shown : undefined; + if (replay) { + return ( + + Run page + + + } + > + {!shown ? null : run && !run.legacy ? ( + run.run.replay ? ( + + ) : ( +

This run has no replay.

+ ) + ) : ( +

{"error" in shown && shown.error}

+ )} +
+ ); + } + return ( - + ); } diff --git a/web/src/ui/ChoiceMenu.tsx b/web/src/ui/ChoiceMenu.tsx index bb683eb..936fcd9 100644 --- a/web/src/ui/ChoiceMenu.tsx +++ b/web/src/ui/ChoiceMenu.tsx @@ -43,16 +43,22 @@ export function ChoiceMenu({ <> {label} {chosen?.label ?? value} - + } // On a phone each menu takes a full row, label on the left and value on the right, so menus of different // widths line up as one column instead of wrapping unevenly. - triggerClassName="border-border bg-surface hover:bg-surface-raised flex h-9 w-full items-center gap-2 rounded-md border px-3 text-sm whitespace-nowrap transition-colors duration-(--duration-fast) sm:inline-flex sm:w-auto" + // Darker than the surface it sits on, like a well, so it reads as a control without competing with the data. + triggerClassName="group border-border bg-bg hover:border-border-strong hover:bg-surface-raised aria-expanded:border-border-strong aria-expanded:bg-surface-raised flex h-9 w-full items-center gap-2 rounded-md border pr-2.5 pl-3 text-sm font-medium whitespace-nowrap transition-colors duration-(--duration-fast) sm:inline-flex sm:w-auto" > {options.map((option) => { const className = classNames( - (option.quiet || option.disabled) && "text-text-subtle", + option.quiet || option.disabled + ? "text-text-subtle" + : "text-text-muted hover:text-text aria-checked:text-accent", option.disabled && "cursor-not-allowed", ); const content = ( diff --git a/web/src/ui/Dialog.tsx b/web/src/ui/Dialog.tsx index 1ef04a2..b9dccc3 100644 --- a/web/src/ui/Dialog.tsx +++ b/web/src/ui/Dialog.tsx @@ -15,12 +15,15 @@ export function Dialog({ title, children, footer, + size = "md", }: { open: boolean; onClose: () => void; title: ReactNode; children: ReactNode; footer?: ReactNode; + /** `lg` for a large view such as a replay. */ + size?: "md" | "lg"; }) { const dialog = useRef(null); const closingQuietly = useRef(false); @@ -62,7 +65,7 @@ export function Dialog({ }} aria-labelledby={titleId} // The element sits wherever its opener is, such as a table cell, and would inherit that text layout. - className="border-border-strong bg-surface text-text shadow-dialog backdrop:bg-bg/75 open:motion-enter m-auto w-[min(100%-2rem,36rem)] rounded-lg border p-0 text-left text-base font-normal whitespace-normal" + className={`border-border-strong bg-surface text-text shadow-dialog backdrop:bg-bg/75 open:motion-enter m-auto rounded-lg border p-0 text-left text-base font-normal whitespace-normal ${size === "lg" ? "w-[min(100%-2rem,64rem)]" : "w-[min(100%-2rem,36rem)]"}`} >

diff --git a/web/src/ui/Menu.tsx b/web/src/ui/Menu.tsx index 7fe8813..2af025d 100644 --- a/web/src/ui/Menu.tsx +++ b/web/src/ui/Menu.tsx @@ -7,6 +7,7 @@ import { type ToggleEvent, useId, useRef, + useState, } from "react"; import { Link } from "./Link"; import { anchoredStyle, anchorStyle } from "./anchor"; @@ -35,6 +36,8 @@ export function Menu({ }) { const id = useId(); const menu = useRef(null); + // Mirrored onto the trigger, so its open look can follow the popover. + const [open, setOpen] = useState(false); const items = () => Array.from( menu.current?.querySelectorAll( @@ -43,6 +46,7 @@ export function Menu({ ); function onToggle(event: ToggleEvent) { + setOpen(event.newState === "open"); if (event.newState === "open") items()[0]?.focus(); } @@ -67,6 +71,7 @@ export function Menu({ type="button" popoverTarget={id} aria-haspopup="menu" + aria-expanded={open} aria-label={label} style={anchorStyle(id)} className={triggerClassName} @@ -95,7 +100,7 @@ export function Menu({ }} // A long list (the Maps page's sorts) scrolls inside the menu rather than running off a short screen. className={classNames( - "border-border-strong bg-surface-overlay text-text shadow-popover motion-pop m-0 mt-2 max-h-[min(28rem,70vh)] min-w-48 overflow-y-auto overscroll-contain rounded-md border p-1 text-sm", + "border-border-strong bg-surface-overlay text-text shadow-popover motion-pop m-0 mt-1 max-h-[min(28rem,70vh)] min-w-44 overflow-y-auto overscroll-contain rounded-lg border p-1 text-sm", matchTriggerWidth && "max-sm:min-w-[anchor-size(width)]", )} > @@ -105,8 +110,9 @@ export function Menu({ ); } +// The overlay is lighter than surface-raised, so hover lifts with a tint of the text color instead. const itemClasses = - "flex h-9 w-full items-center gap-2 rounded-sm px-3 text-left outline-none hover:bg-surface-raised focus-visible:bg-surface-raised [&_svg]:size-4 [&_svg]:text-text-muted"; + "flex h-8 w-full items-center gap-2 rounded-md px-2.5 text-left outline-none transition-colors duration-(--duration-fast) hover:bg-text/8 focus-visible:bg-text/8 [&_svg]:size-4 [&_svg]:text-text-muted aria-checked:[&_svg]:text-accent"; export function MenuItem({ className, ...props }: ComponentProps<"button">) { return ( @@ -132,5 +138,5 @@ export function MenuLink({ className, ...props }: ComponentProps) { } export function MenuSeparator() { - return
; + return
; } diff --git a/web/src/ui/Page.tsx b/web/src/ui/Page.tsx index 3747f87..2b8891e 100644 --- a/web/src/ui/Page.tsx +++ b/web/src/ui/Page.tsx @@ -13,10 +13,10 @@ export function Page({ children, }: { /** - * `narrow` is a reading width for text-heavy pages. `fill` is for pages inside a section layout that + * `narrow` is a reading width for text-heavy pages; `medium` for a single table that would stretch thin. `fill` is for pages inside a section layout that * already sets the width and padding, such as the staff area with its sidebar. */ - width?: "wide" | "narrow" | "fill"; + width?: "wide" | "medium" | "narrow" | "fill"; className?: string; children: ReactNode; }) { @@ -27,6 +27,7 @@ export function Page({ "flex w-full flex-1 flex-col", width === "fill" ? "min-w-0" : "mx-auto px-4 py-10", width === "narrow" && "max-w-3xl", + width === "medium" && "max-w-4xl", width === "wide" && "max-w-6xl", className, )} diff --git a/web/src/ui/Pager.tsx b/web/src/ui/Pager.tsx index e1cd260..1af7ba0 100644 --- a/web/src/ui/Pager.tsx +++ b/web/src/ui/Pager.tsx @@ -1,39 +1,165 @@ -// Previous and next links under a paged list, with where the reader is. +// Page links under a paged list: both ends, the current page and its neighbours, and a box for going straight to +// a page. import { ChevronLeft, ChevronRight } from "lucide-react"; -import { ButtonLink } from "./Button"; +import Form from "next/form"; +import { type ReactNode, useId } from "react"; +import { classNames } from "./classNames"; +import { Link } from "./Link"; -/** Renders nothing when everything fits on one page. Pages count from 1. */ +const PARAM = "page"; + +const cell = + "inline-flex h-8 min-w-8 items-center justify-center rounded-md px-2 text-sm tabular-nums transition-colors duration-(--duration-fast)"; +const link = "text-text-muted hover:bg-text/6 hover:text-text"; +const number = new Intl.NumberFormat("en"); + +/** + * Renders nothing when everything fits on one page. Pages count from 1 and sit in the address as `?page=`, so + * `href(1)` also gives the address the box keeps. A list whose length isn't known yet passes the pages loaded so + * far and `more`, and its last page shows as a gap. + */ export function Pager({ page, pageCount, + more = false, + total, + noun, href, }: { page: number; pageCount: number; + more?: boolean; + /** How many items there are in all, shown before the page with `noun`: "3,599 runs". */ + total?: number; + noun?: string; href: (page: number) => string; }) { - if (pageCount <= 1) return null; + const box = useId(); + if (pageCount <= 1 && !more) return null; + const last = more ? pageCount + 1 : pageCount; + const shown = [ + ...new Set([1, page - 1, page, page + 1, ...(more ? [] : [pageCount])]), + ] + .filter((p) => p >= 1 && p <= last) + .sort((a, b) => a - b); + const base = new URL(href(1), "http://site"); + base.searchParams.delete(PARAM); + + const items = []; + let previous = 0; + for (const p of shown) { + if (p - previous > 1) items.push(); + items.push( + + {p} + , + ); + previous = p; + } + if (more) items.push(); + return ( -