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..9b6481f 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,322 @@ import {
} from "@/ui/Table";
import { TierBadge } from "@/ui/TierBadge";
-type Page = Schemas["RecentRuns"];
+type Runs = Schemas["RecentRuns"];
type Query = {
style?: string;
track?: "main" | "bonus";
min_tier?: number;
records?: boolean;
+ limit?: number;
};
export function RecentRunTable({
first,
query,
+ address,
+ pageSize,
styleNames,
showStyle,
}: {
- first: Page;
- /** The filters `first` was loaded with, for loading the pages after it. */
+ /** The newest runs, enough to reach `page`. */
+ first: Runs;
+ /** The filters `first` was loaded with, for loading the runs after it. */
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 [cursor, setCursor] = useState(first.next_cursor ?? null);
const [failed, setFailed] = useState(false);
+ const [waiting, setWaiting] = useState(false);
+ const [turned, setTurned] = useState(false);
+ // The latest runs and cursor for the loops below, which outlive the render that started them.
+ const latest = useRef({
+ runs: first.runs,
+ cursor: first.next_cursor ?? null,
+ });
+ const inFlight = useRef | null>(null);
+ 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.tier_count;
- async function showMore(after: string) {
- setLoading(true);
- setFailed(false);
- const loaded = await api
+ // The address holds the page, so a reload, a shared link and the back button all land on it.
+ // 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 pageCount = Math.max(1, Math.ceil(runs.length / pageSize));
+ const page = Math.min(asked, pageCount);
+ const shown = runs.slice((page - 1) * pageSize, page * pageSize);
+
+ const pageHref = useCallback(
+ (p: number) =>
+ p > 1
+ ? `${address}${address.includes("?") ? "&" : "?"}page=${p}`
+ : address,
+ [address],
+ );
+
+ /** Loads the next hundred runs, once however many ask; false when there are none or they failed. */
+ const loadMore = useCallback((): Promise => {
+ if (inFlight.current) return inFlight.current;
+ const after = latest.current.cursor;
+ if (!after) return Promise.resolve(false);
+ inFlight.current = api
.GET("/v1/runs", { params: { query: { ...query, cursor: after } } })
.then((result) => result.data)
- .catch(() => undefined);
- setLoading(false);
- if (!loaded) {
- setFailed(true);
- return;
+ .catch(() => undefined)
+ .then((next) => {
+ inFlight.current = null;
+ setFailed(!next);
+ if (!next) return false;
+ latest.current = {
+ runs: [...latest.current.runs, ...next.runs],
+ cursor: next.next_cursor ?? null,
+ };
+ setRuns(latest.current.runs);
+ setCursor(latest.current.cursor);
+ return true;
+ });
+ return inFlight.current;
+ }, [query]);
+
+ // Keeps a few pages loaded past the one asked for, so Next never waits. An address past what's loaded, as
+ // after going back to a far page, walks forward to it the same way.
+ useEffect(() => {
+ if (cursor && !failed && runs.length < (asked + 4) * pageSize)
+ void loadMore();
+ }, [cursor, failed, runs.length, asked, pageSize, loadMore]);
+
+ // Past the last run, the address is corrected to the last page rather than showing one page and naming another.
+ useEffect(() => {
+ if (!cursor && asked > pageCount)
+ window.history.replaceState(null, "", pageHref(pageCount));
+ }, [cursor, asked, pageCount, pageHref]);
+
+ async function go(target: number) {
+ const turn = ++turns.current;
+ // A typed page past what's loaded walks forward to it, or to the last page if the runs end first.
+ while (latest.current.runs.length < target * pageSize) {
+ setWaiting(true);
+ if (!(await loadMore())) break;
}
- 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 count = Math.max(1, Math.ceil(latest.current.runs.length / pageSize));
+ const next = pageHref(Math.min(target, count));
+ 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));
+ }
+
+ 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 (runs.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,32 @@ export async function RecentRuns({ params }: { params: RecentRunsParams }) {
);
}
+
+/** Runs from the newest, enough to reach `page`; undefined when the first request fails. */
+async function loadRuns(
+ query: RunsQuery,
+ page: number,
+): Promise {
+ const get = (cursor?: string) =>
+ api
+ .GET("/v1/runs", {
+ params: { query: { ...query, limit: CHUNK, cursor } },
+ })
+ .then((result) => result.data)
+ .catch(() => undefined);
+ const first = await get();
+ if (!first) return undefined;
+ const runs = [...first.runs];
+ let cursor = first.next_cursor;
+ for (
+ let chunk = 1;
+ cursor && runs.length < page * PAGE_SIZE && chunk < MAX_CHUNKS;
+ chunk++
+ ) {
+ const next = await get(cursor);
+ if (!next) break;
+ runs.push(...next.runs);
+ cursor = next.next_cursor;
+ }
+ return { ...first, runs, next_cursor: cursor };
+}
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. */}
+