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 (
-
-
);
}
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. */}
+
- ) : (
- –
- )}
-
-
- ))}
-
-
+ 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. */}
+