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..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. */} + - ) : ( - – - )} - - - ))} - -
-
- {failed && ( - - More couldn't be loaded. Try again. - - )} - {cursor && ( - - )} + + + + + + {run.world_record ? ( + WR + ) : run.placement != null ? ( + + + + ) : ( + – + )} + + + ))} + +
+ {(pageCount > 1 || cursor) && ( +
+ +
+ )} + {failed && ( +

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

+ )}
); } diff --git a/web/src/features/activity/RecentRuns.tsx b/web/src/features/activity/RecentRuns.tsx index 87ba140..bd076dc 100644 --- a/web/src/features/activity/RecentRuns.tsx +++ b/web/src/features/activity/RecentRuns.tsx @@ -1,5 +1,5 @@ // The Activity page's runs: the filter menus, read from and written to the address, and the first page of runs. -import { api } from "@/api/client"; +import { api, type Schemas } from "@/api/client"; import { currentStyles } from "@/features/ruleset/styles"; import { ChoiceBar } from "@/ui/ChoiceBar"; import { ChoiceMenu } from "@/ui/ChoiceMenu"; @@ -19,8 +19,22 @@ export interface RecentRunsParams { tier?: string; /** "records": world records only. */ show?: string; + page?: string; } +const PAGE_SIZE = 15; +/** Runs per request. A hundred cost the API about what fifteen do, so most pages turn without a request. */ +const CHUNK = 100; +/** How far a typed page number may walk before giving up, at one request per hundred runs. */ +const MAX_CHUNKS = 20; + +type RunsQuery = { + style?: string; + track?: "main" | "bonus"; + min_tier?: number; + records?: boolean; +}; + interface Filters { style?: string; track: Track; @@ -29,23 +43,30 @@ 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 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?.tier_count ?? undefined; // Only what differs from the defaults goes in the address, so the plain page stays /activity. @@ -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,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. */} +
+ {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 ( -