From 58d29720814b61a71a6322e8a6fc8d6fce3d8085 Mon Sep 17 00:00:00 2001 From: zasbu <136494048+zasbu@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:07:57 +1100 Subject: [PATCH 1/4] Improve maps pages and map summaries --- ...b343ca18be82be0ae291192fb51553d169faa.json | 28 --- ...9f91cac3b29f0211e6db655536f3c7eb9ec28.json | 29 +++ ...6dc1326618003da8ee7441ed60865af2775a7.json | 191 ++++++++++++++++ ...dcb41391bbe8710c67fe523098acc3af22b33.json | 190 ---------------- api/crates/api/src/maps/list.rs | 110 ++++++++- api/openapi.json | 2 +- docs/site-api.md | 4 +- web/e2e/maps-cards.e2e.ts | 176 ++++++++++++-- web/e2e/maps-overview.e2e.ts | 214 +++++++++++++++--- web/src/api/schema.ts | 6 +- web/src/features/maps/MapCard.module.css | 47 ++-- web/src/features/maps/MapCard.tsx | 177 ++++++++++----- web/src/features/maps/MapImage.tsx | 6 +- web/src/features/maps/MapList.tsx | 188 ++++++++------- web/src/features/maps/MapOverview.module.css | 160 +++++++++++++ web/src/features/maps/mapPodiums.test.ts | 82 +++++++ web/src/features/maps/mapPodiums.ts | 40 +++- web/src/ui/TierSpread.tsx | 62 ++--- 18 files changed, 1213 insertions(+), 499 deletions(-) delete mode 100644 api/.sqlx/query-0b0d82934ef77f36365f54641adb343ca18be82be0ae291192fb51553d169faa.json create mode 100644 api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json create mode 100644 api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json delete mode 100644 api/.sqlx/query-e9f09b3277fa13f62738502dad4dcb41391bbe8710c67fe523098acc3af22b33.json create mode 100644 web/src/features/maps/MapOverview.module.css create mode 100644 web/src/features/maps/mapPodiums.test.ts diff --git a/api/.sqlx/query-0b0d82934ef77f36365f54641adb343ca18be82be0ae291192fb51553d169faa.json b/api/.sqlx/query-0b0d82934ef77f36365f54641adb343ca18be82be0ae291192fb51553d169faa.json deleted file mode 100644 index b22cab5..0000000 --- a/api/.sqlx/query-0b0d82934ef77f36365f54641adb343ca18be82be0ae291192fb51553d169faa.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT count(*) AS \"count!\" FROM maps m\n WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\\' OR $2 <% name)\n AND ($3::bigint IS NULL OR $4 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "count!", - "type_info": "Int8", - "origin": "Expression" - } - ], - "parameters": { - "Left": [ - "Text", - "Text", - "Int8", - "Bool", - "Text", - "Int2" - ] - }, - "nullable": [ - null - ] - }, - "hash": "0b0d82934ef77f36365f54641adb343ca18be82be0ae291192fb51553d169faa" -} diff --git a/api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json b/api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json new file mode 100644 index 0000000..6db845f --- /dev/null +++ b/api/.sqlx/query-812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT count(*) AS \"count!\" FROM maps m\n WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\\' OR $2 <% name\n OR EXISTS (SELECT 1 FROM world_record_holders h JOIN players p ON p.steamid64 = h.player_steamid64\n WHERE h.map_id = m.id AND h.style = $5 AND h.track = 0 AND p.name ILIKE $7 ESCAPE '\\'))\n AND ($3::bigint IS NULL OR $4 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "count!", + "type_info": "Int8", + "origin": "Expression" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "Bool", + "Text", + "Int2", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "812bc73f084e7a5f90687cc457d9f91cac3b29f0211e6db655536f3c7eb9ec28" +} diff --git a/api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json b/api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json new file mode 100644 index 0000000..0d333b9 --- /dev/null +++ b/api/.sqlx/query-bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7.json @@ -0,0 +1,191 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH holder_maps AS (\n SELECT h.map_id FROM world_record_holders h\n JOIN players p ON p.steamid64 = h.player_steamid64\n WHERE $11::text IS NOT NULL AND h.style = $5 AND h.track = 0\n AND p.name ILIKE $11 ESCAPE '\\'\n ), listed AS (\n SELECT m.id, m.name, m.last_run_at, m.players, tier.tier,\n row_number() OVER (ORDER BY\n -- How well the name matches: exactly, by a word's start (\"candy\" in bhop_candy), or within.\n CASE WHEN $6::text IS NULL OR m.name = $6 THEN 0\n WHEN starts_with(m.name, $6) OR strpos(m.name, '_' || $6) > 0 THEN 1\n WHEN m.name ILIKE $1 ESCAPE '\\' THEN 2\n WHEN m.id IN (SELECT map_id FROM holder_maps) THEN 3 ELSE 4 END,\n CASE WHEN m.name NOT ILIKE $1 ESCAPE '\\' AND $7 <% m.name\n THEN word_similarity($7, m.name) END DESC NULLS LAST,\n CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC,\n CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST,\n CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END,\n CASE $2 WHEN 'hardest' THEN -tier.tier WHEN 'easiest' THEN tier.tier END NULLS LAST,\n CASE $2 WHEN 'longest_record' THEN -record.time WHEN 'shortest_record' THEN record.time END\n NULLS LAST,\n CASE WHEN $2 = 'newest_record' THEN record.finished_at END DESC NULLS LAST,\n CASE WHEN $2 = 'oldest_record' THEN record.finished_at END NULLS LAST,\n CASE WHEN $2 = 'name_desc' THEN m.name END DESC,\n m.name\n ) AS position\n FROM maps m\n LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0\n -- Every map's record, read only for the sorts that need it: the page below reads the page's own.\n LEFT JOIN LATERAL (\n SELECT pb.time, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE $2 IN ('longest_record', 'shortest_record', 'newest_record', 'oldest_record') AND pb.map_id = m.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) record ON true\n WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\\'\n OR $7 <% m.name OR m.id IN (SELECT map_id FROM holder_maps))\n AND ($8::bigint IS NULL OR $9 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($10::smallint IS NULL OR tier.tier = $10)\n ), page AS (\n SELECT * FROM listed WHERE position > $4 ORDER BY position LIMIT $3\n )\n SELECT page.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", page.last_run_at AS \"last_run_at!\", page.players::int8 AS \"players!\",\n counts.bonuses AS \"bonuses!\", page.tier AS \"tier?\",\n wr.time AS \"wr_time?\", wr.run_id AS \"wr_run_id?\", wr.finished_at AS \"wr_finished_at?\",\n p.steamid64::text AS \"wr_steamid64?\", p.name AS \"wr_name?\", p.avatar_url AS \"wr_avatar_url?\",\n p.country_code AS \"wr_country_code?\"\n FROM page\n LEFT JOIN map_images ci ON ci.map_id = page.id AND ci.position = 0\n CROSS JOIN LATERAL (\n SELECT count(DISTINCT track) FILTER (WHERE track > 0) AS bonuses\n FROM personal_bests WHERE map_id = page.id\n ) counts\n LEFT JOIN LATERAL (\n SELECT pb.player_steamid64, pb.time, pb.run_id, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE pb.map_id = page.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) wr ON true\n LEFT JOIN players p ON p.steamid64 = wr.player_steamid64\n ORDER BY page.position\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Text", + "origin": { + "Table": { + "table": "maps", + "name": "name" + } + } + }, + { + "ordinal": 1, + "name": "image_id?", + "type_info": "Int8", + "origin": { + "Table": { + "table": "map_images", + "name": "id" + } + } + }, + { + "ordinal": 2, + "name": "image_key?", + "type_info": "Text", + "origin": { + "Table": { + "table": "map_images", + "name": "key" + } + } + }, + { + "ordinal": 3, + "name": "image_focus?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "map_images", + "name": "focus" + } + } + }, + { + "ordinal": 4, + "name": "last_run_at!", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "maps", + "name": "last_run_at" + } + } + }, + { + "ordinal": 5, + "name": "players!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 6, + "name": "bonuses!", + "type_info": "Int8", + "origin": "Expression" + }, + { + "ordinal": 7, + "name": "tier?", + "type_info": "Int2", + "origin": { + "Table": { + "table": "current_map_tiers", + "name": "tier" + } + } + }, + { + "ordinal": 8, + "name": "wr_time?", + "type_info": "Float8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "time" + } + } + }, + { + "ordinal": 9, + "name": "wr_run_id?", + "type_info": "Int8", + "origin": { + "Table": { + "table": "personal_bests", + "name": "run_id" + } + } + }, + { + "ordinal": 10, + "name": "wr_finished_at?", + "type_info": "Timestamptz", + "origin": { + "Table": { + "table": "runs", + "name": "finished_at" + } + } + }, + { + "ordinal": 11, + "name": "wr_steamid64?", + "type_info": "Text", + "origin": "Expression" + }, + { + "ordinal": 12, + "name": "wr_name?", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "name" + } + } + }, + { + "ordinal": 13, + "name": "wr_avatar_url?", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "avatar_url" + } + } + }, + { + "ordinal": 14, + "name": "wr_country_code?", + "type_info": "Text", + "origin": { + "Table": { + "table": "players", + "name": "country_code" + } + } + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "Int8", + "Text", + "Text", + "Text", + "Int8", + "Bool", + "Int2", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + true, + null, + null, + true, + true, + true, + true, + null, + true, + true, + true + ] + }, + "hash": "bf0b6142252f2a50b0f7709347f6dc1326618003da8ee7441ed60865af2775a7" +} diff --git a/api/.sqlx/query-e9f09b3277fa13f62738502dad4dcb41391bbe8710c67fe523098acc3af22b33.json b/api/.sqlx/query-e9f09b3277fa13f62738502dad4dcb41391bbe8710c67fe523098acc3af22b33.json deleted file mode 100644 index e61c244..0000000 --- a/api/.sqlx/query-e9f09b3277fa13f62738502dad4dcb41391bbe8710c67fe523098acc3af22b33.json +++ /dev/null @@ -1,190 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n WITH listed AS (\n SELECT m.id, m.name, m.last_run_at, m.players, tier.tier,\n row_number() OVER (ORDER BY\n -- How well the name matches: exactly, by a word's start (\"candy\" in bhop_candy), or within.\n CASE WHEN $6::text IS NULL OR m.name = $6 THEN 0\n WHEN starts_with(m.name, $6) OR strpos(m.name, '_' || $6) > 0 THEN 1\n WHEN m.name ILIKE $1 ESCAPE '\\' THEN 2 ELSE 3 END,\n CASE WHEN m.name NOT ILIKE $1 ESCAPE '\\' THEN word_similarity($7, m.name) END DESC NULLS LAST,\n CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC,\n CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST,\n CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END,\n CASE $2 WHEN 'hardest' THEN -tier.tier WHEN 'easiest' THEN tier.tier END NULLS LAST,\n CASE $2 WHEN 'longest_record' THEN -record.time WHEN 'shortest_record' THEN record.time END\n NULLS LAST,\n CASE WHEN $2 = 'newest_record' THEN record.finished_at END DESC NULLS LAST,\n CASE WHEN $2 = 'oldest_record' THEN record.finished_at END NULLS LAST,\n CASE WHEN $2 = 'name_desc' THEN m.name END DESC,\n m.name\n ) AS position\n FROM maps m\n LEFT JOIN current_map_tiers tier ON tier.map_id = m.id AND tier.track = 0\n -- Every map's record, read only for the sorts that need it: the page below reads the page's own.\n LEFT JOIN LATERAL (\n SELECT pb.time, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE $2 IN ('longest_record', 'shortest_record', 'newest_record', 'oldest_record') AND pb.map_id = m.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) record ON true\n WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\\' OR $7 <% m.name)\n AND ($8::bigint IS NULL OR $9 = EXISTS (\n SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0))\n AND ($10::smallint IS NULL OR tier.tier = $10)\n ), page AS (\n SELECT * FROM listed WHERE position > $4 ORDER BY position LIMIT $3\n )\n SELECT page.name, ci.id AS \"image_id?\", ci.key AS \"image_key?\", ci.focus AS \"image_focus?\", page.last_run_at AS \"last_run_at!\", page.players::int8 AS \"players!\",\n counts.bonuses AS \"bonuses!\", page.tier AS \"tier?\",\n wr.time AS \"wr_time?\", wr.run_id AS \"wr_run_id?\", wr.finished_at AS \"wr_finished_at?\",\n p.steamid64::text AS \"wr_steamid64?\", p.name AS \"wr_name?\", p.avatar_url AS \"wr_avatar_url?\",\n p.country_code AS \"wr_country_code?\"\n FROM page\n LEFT JOIN map_images ci ON ci.map_id = page.id AND ci.position = 0\n CROSS JOIN LATERAL (\n SELECT count(DISTINCT track) FILTER (WHERE track > 0) AS bonuses\n FROM personal_bests WHERE map_id = page.id\n ) counts\n LEFT JOIN LATERAL (\n SELECT pb.player_steamid64, pb.time, pb.run_id, r.finished_at\n FROM personal_bests pb JOIN runs r ON r.id = pb.run_id\n WHERE pb.map_id = page.id AND pb.style = $5 AND pb.track = 0\n ORDER BY pb.time, r.finished_at\n LIMIT 1\n ) wr ON true\n LEFT JOIN players p ON p.steamid64 = wr.player_steamid64\n ORDER BY page.position\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "name", - "type_info": "Text", - "origin": { - "Table": { - "table": "maps", - "name": "name" - } - } - }, - { - "ordinal": 1, - "name": "image_id?", - "type_info": "Int8", - "origin": { - "Table": { - "table": "map_images", - "name": "id" - } - } - }, - { - "ordinal": 2, - "name": "image_key?", - "type_info": "Text", - "origin": { - "Table": { - "table": "map_images", - "name": "key" - } - } - }, - { - "ordinal": 3, - "name": "image_focus?", - "type_info": "Int2", - "origin": { - "Table": { - "table": "map_images", - "name": "focus" - } - } - }, - { - "ordinal": 4, - "name": "last_run_at!", - "type_info": "Timestamptz", - "origin": { - "Table": { - "table": "maps", - "name": "last_run_at" - } - } - }, - { - "ordinal": 5, - "name": "players!", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 6, - "name": "bonuses!", - "type_info": "Int8", - "origin": "Expression" - }, - { - "ordinal": 7, - "name": "tier?", - "type_info": "Int2", - "origin": { - "Table": { - "table": "current_map_tiers", - "name": "tier" - } - } - }, - { - "ordinal": 8, - "name": "wr_time?", - "type_info": "Float8", - "origin": { - "Table": { - "table": "personal_bests", - "name": "time" - } - } - }, - { - "ordinal": 9, - "name": "wr_run_id?", - "type_info": "Int8", - "origin": { - "Table": { - "table": "personal_bests", - "name": "run_id" - } - } - }, - { - "ordinal": 10, - "name": "wr_finished_at?", - "type_info": "Timestamptz", - "origin": { - "Table": { - "table": "runs", - "name": "finished_at" - } - } - }, - { - "ordinal": 11, - "name": "wr_steamid64?", - "type_info": "Text", - "origin": "Expression" - }, - { - "ordinal": 12, - "name": "wr_name?", - "type_info": "Text", - "origin": { - "Table": { - "table": "players", - "name": "name" - } - } - }, - { - "ordinal": 13, - "name": "wr_avatar_url?", - "type_info": "Text", - "origin": { - "Table": { - "table": "players", - "name": "avatar_url" - } - } - }, - { - "ordinal": 14, - "name": "wr_country_code?", - "type_info": "Text", - "origin": { - "Table": { - "table": "players", - "name": "country_code" - } - } - } - ], - "parameters": { - "Left": [ - "Text", - "Text", - "Int8", - "Int8", - "Text", - "Text", - "Text", - "Int8", - "Bool", - "Int2" - ] - }, - "nullable": [ - false, - false, - false, - false, - true, - null, - null, - true, - true, - true, - true, - null, - true, - true, - true - ] - }, - "hash": "e9f09b3277fa13f62738502dad4dcb41391bbe8710c67fe523098acc3af22b33" -} diff --git a/api/crates/api/src/maps/list.rs b/api/crates/api/src/maps/list.rs index 830d02d..beb6771 100644 --- a/api/crates/api/src/maps/list.rs +++ b/api/crates/api/src/maps/list.rs @@ -24,9 +24,9 @@ const MAX_LIMIT: i64 = 100; #[derive(Debug, Deserialize, IntoParams)] pub struct MapsQuery { - /// Part of a map name. Case doesn't matter, and spaces stand for underscores. The map of exactly that - /// name comes first, then maps with a word starting with it, then other matches, each in the chosen - /// sort; near misses for a typo come last, closest first. + /// Part of a map name or a main-track world record holder's name in the chosen style. Case doesn't + /// matter; spaces in map names stand for underscores. Exact map names come first, then word starts, + /// other map matches and record holders, each in the chosen sort; near misses come last. q: Option, /// Default `name`. #[param(inline)] @@ -193,6 +193,12 @@ pub async fn list_maps( let sort = query.sort.unwrap_or(MapSort::Name).key(); let search = query.q.as_deref().and_then(search_name); let pattern = search.as_deref().map(name_search::contains_pattern); + let holder_pattern = query + .q + .as_deref() + .map(str::trim) + .filter(|q| !q.is_empty()) + .map(name_search::contains_pattern); // Most map names start with "bhop_", which would make every map a near miss of every search. let near = search .as_deref() @@ -205,6 +211,7 @@ pub async fn list_maps( }; let filter = Filter { pattern: pattern.as_deref(), + holder_pattern: holder_pattern.as_deref(), near, style: style.as_deref(), completed_by: query.completed.and(player).map(SteamId64::get), @@ -385,14 +392,21 @@ async fn listed_page( sqlx::query_as!( ListedMap, r#" - WITH listed AS ( + WITH holder_maps AS ( + SELECT h.map_id FROM world_record_holders h + JOIN players p ON p.steamid64 = h.player_steamid64 + WHERE $11::text IS NOT NULL AND h.style = $5 AND h.track = 0 + AND p.name ILIKE $11 ESCAPE '\' + ), listed AS ( SELECT m.id, m.name, m.last_run_at, m.players, tier.tier, row_number() OVER (ORDER BY -- How well the name matches: exactly, by a word's start ("candy" in bhop_candy), or within. CASE WHEN $6::text IS NULL OR m.name = $6 THEN 0 WHEN starts_with(m.name, $6) OR strpos(m.name, '_' || $6) > 0 THEN 1 - WHEN m.name ILIKE $1 ESCAPE '\' THEN 2 ELSE 3 END, - CASE WHEN m.name NOT ILIKE $1 ESCAPE '\' THEN word_similarity($7, m.name) END DESC NULLS LAST, + WHEN m.name ILIKE $1 ESCAPE '\' THEN 2 + WHEN m.id IN (SELECT map_id FROM holder_maps) THEN 3 ELSE 4 END, + CASE WHEN m.name NOT ILIKE $1 ESCAPE '\' AND $7 <% m.name + THEN word_similarity($7, m.name) END DESC NULLS LAST, CASE WHEN $2 = 'recent' THEN m.last_run_at END DESC, CASE WHEN $2 = 'newest' THEN m.listed_at END DESC NULLS LAST, CASE $2 WHEN 'popular' THEN -m.players WHEN 'least_popular' THEN m.players END, @@ -414,7 +428,8 @@ async fn listed_page( ORDER BY pb.time, r.finished_at LIMIT 1 ) record ON true - WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\' OR $7 <% m.name) + WHERE m.last_run_at IS NOT NULL AND ($1::text IS NULL OR m.name ILIKE $1 ESCAPE '\' + OR $7 <% m.name OR m.id IN (SELECT map_id FROM holder_maps)) AND ($8::bigint IS NULL OR $9 = EXISTS ( SELECT 1 FROM personal_bests WHERE player_steamid64 = $8 AND map_id = m.id AND style = $5 AND track = 0)) AND ($10::smallint IS NULL OR tier.tier = $10) @@ -451,7 +466,8 @@ async fn listed_page( filter.near, filter.completed_by, filter.completed, - filter.tier + filter.tier, + filter.holder_pattern ) .fetch_all(tx) .await @@ -508,6 +524,8 @@ impl ListedMap { struct Filter<'a> { /// The search as an `ILIKE` pattern. pattern: Option<&'a str>, + /// The original search, preserving spaces in player names. + holder_pattern: Option<&'a str>, /// The search's term for near misses. near: Option<&'a str>, style: Option<&'a str>, @@ -522,7 +540,9 @@ struct Filter<'a> { async fn count_maps(tx: &mut sqlx::PgConnection, filter: &Filter<'_>) -> Result { sqlx::query_scalar!( r#"SELECT count(*) AS "count!" FROM maps m - WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\' OR $2 <% name) + WHERE last_run_at IS NOT NULL AND ($1::text IS NULL OR name ILIKE $1 ESCAPE '\' OR $2 <% name + OR EXISTS (SELECT 1 FROM world_record_holders h JOIN players p ON p.steamid64 = h.player_steamid64 + WHERE h.map_id = m.id AND h.style = $5 AND h.track = 0 AND p.name ILIKE $7 ESCAPE '\')) AND ($3::bigint IS NULL OR $4 = EXISTS ( SELECT 1 FROM personal_bests WHERE player_steamid64 = $3 AND map_id = m.id AND style = $5 AND track = 0)) AND ($6::smallint IS NULL OR $6 = (SELECT tier FROM current_map_tiers WHERE map_id = m.id AND track = 0))"#, @@ -531,7 +551,8 @@ async fn count_maps(tx: &mut sqlx::PgConnection, filter: &Filter<'_>) -> Result< filter.completed_by, filter.completed, filter.style, - filter.tier + filter.tier, + filter.holder_pattern ) .fetch_one(tx) .await @@ -636,6 +657,73 @@ mod tests { ); } + #[sqlx::test] + async fn searches_current_main_track_record_holders_in_the_selected_style(db: PgPool) { + let key = setup(&db).await; + sqlx::query( + r#"INSERT INTO rulesets (version, document) + SELECT 2, jsonb_set(document, '{styles}', + (document->'styles') || '[{"key":"sw","name":"Sideways","settings":{}}]'::jsonb) + FROM rulesets WHERE version = 1"#, + ) + .execute(&db) + .await + .unwrap(); + for (id, map, player, name, time, style, track) in [ + ( + "holder-main", + "bhop_badges", + 0, + "Speed Runner", + 30.0, + "normal", + 0, + ), + ( + "holder-second", + "bhop_arcane", + 0, + "Speed Runner", + 15.0, + "normal", + 0, + ), + ("slower", "bhop_badges", 1, "Bonus Hero", 40.0, "normal", 0), + ("bonus", "bhop_badges", 1, "Bonus Hero", 10.0, "normal", 1), + ("sideways", "bhop_badges", 1, "Bonus Hero", 20.0, "sw", 0), + ("tied", "bhop_badges", 2, "Co Holder", 30.0, "normal", 0), + ] { + let mut body = run(id, time); + body["map"] = json!(map); + body["player"] = json!({ + "steamid64": (76_561_197_960_287_930_i64 + player).to_string(), + "name": name, + }); + body["style"] = json!(style); + body["track"] = json!(track); + body["ruleset_version"] = json!(2); + assert_eq!( + test_client::post(&db, "/v1/runs", Some(&key), &body) + .await + .status, + 201 + ); + } + let page: MapList = test_client::get(&db, "/v1/maps?q=SPEED%20RUNNER&limit=1&offset=1") + .await + .json(); + assert_eq!(page.total, 2); + assert_eq!(page.maps.len(), 1); + assert_eq!(page.maps[0].name, "bhop_badges"); + assert_eq!(names(&db, "/v1/maps?q=Co%20Holder").await, ["bhop_badges"]); + assert_eq!(names(&db, "/v1/maps?q=Bonus%20Hero").await.len(), 0); + assert_eq!( + names(&db, "/v1/maps?q=Bonus%20Hero&style=sw").await, + ["bhop_badges"] + ); + assert_eq!(names(&db, "/v1/maps?q=%25").await.len(), 0); + } + /// `bhop_badges`' stored player count, and the count its personal bests give. async fn badges_players(db: &PgPool) -> (i32, i64) { sqlx::query_as( @@ -741,7 +829,7 @@ mod tests { let mut body = run(&format!("tier-{index}-{player}"), 30.0); body["map"] = json!(name); body["player"] = json!({ - "steamid64": (76561197960287930_i64 + player).to_string(), + "steamid64": (76_561_197_960_287_930_i64 + player).to_string(), "name": format!("player-{player}"), }); assert_eq!( diff --git a/api/openapi.json b/api/openapi.json index ff67698..38076b7 100644 --- a/api/openapi.json +++ b/api/openapi.json @@ -588,7 +588,7 @@ { "name": "q", "in": "query", - "description": "Part of a map name. Case doesn't matter, and spaces stand for underscores. The map of exactly that\nname comes first, then maps with a word starting with it, then other matches, each in the chosen\nsort; near misses for a typo come last, closest first.", + "description": "Part of a map name or a main-track world record holder's name in the chosen style. Case doesn't\nmatter; spaces in map names stand for underscores. Exact map names come first, then word starts,\nother map matches and record holders, each in the chosen sort; near misses come last.", "required": false, "schema": { "type": [ diff --git a/docs/site-api.md b/docs/site-api.md index fd522f8..c66f82a 100644 --- a/docs/site-api.md +++ b/docs/site-api.md @@ -2,7 +2,7 @@ The website's endpoints; staff tools: `staff-api.md`. Rules for every client and game servers' endpoints: `api.md`. ## Sign-in and sessions -Players sign in with Steam (OpenID 2.0); the endpoints answer browsers (redirects, cookies) via the site's origin. +Steam OpenID sign-in uses the configured site origin for cookies and callbacks, canonicalizing aliases first. - Steam must confirm its answer (`check_authentication`). Only signed fields are read, the return URL must be our callback, a nonce works once, within 5 minutes (`openid_nonces`). The callback must carry the value `/v1/auth/steam` put in the `sj_sign_in` cookie, tying sign-in to its browser. Refused: `/sign-in/failed`; cancelled: back where they were. - `return_to` must be a path on our site; anything else becomes `/`. - A session is 32 random bytes in the `sj_session` cookie (`HttpOnly; Secure; SameSite=Lax`); only its SHA-256 is stored. It lasts 30 days from last use (expiry moves at most daily). @@ -19,7 +19,7 @@ Players sign in with Steam (OpenID 2.0); the endpoints answer browsers (redirect - Staff privileges: a bitmap in `players.privileges` (`players/privileges.rs`); bit positions never change; the API names them, never numbers. `players.restrictions` is unused (bans hold restrictions). The CLI's `privileges grant …`, `revoke`, `list` and the staff tools share `staff/privileges.rs`. ## Maps and leaderboards -- Maps with runs (`maps.last_run_at`, set on ingest); ranking is open. Sorts: name, players, last/first run (`listed_at`), tier and main-track WR. `tier` keeps one main tier. `player` (any SteamID) with `completed=true|false` filters the style's main-track completions; `completed` counts them. `stats` totals stay global; newest and weekly lists take five within `stats.tier` (null: all). Weekly ranks count distinct players. +- Maps with runs (`maps.last_run_at`). `q` searches map names and the style's main WR holders. Sorts: name, players, last/first run (`listed_at`), tier and main WR. `tier` keeps one main tier. `player` (any SteamID) with `completed=true|false` filters the style's main completions; `completed` counts them. Global `stats` totals; newest and weekly lists take five within `stats.tier` (null: all). Weekly counts distinct players. - Leaderboards rank PBs per map, style and track; equal times share a place, the earlier run listed first. A tie's world record belongs to whoever set it first. - `GET /v1/maps/{map}` carries every style and track's top 25, `next_cursor` and WR history, for map pages to switch locally. `…/leaderboard?cursor=` pages on from there; cursors are opaque. - WR history: every run faster than all finished before it on that board, by `finished_at`; ties don't count. diff --git a/web/e2e/maps-cards.e2e.ts b/web/e2e/maps-cards.e2e.ts index a4171c7..f600667 100644 --- a/web/e2e/maps-cards.e2e.ts +++ b/web/e2e/maps-cards.e2e.ts @@ -58,6 +58,111 @@ test("cards show the API's top three for the chosen style", async ({ ).toBeVisible(); } await expectTextInside(card); + const preview = await card.evaluate((element) => { + const cover = element.firstElementChild!; + const image = cover.firstElementChild!; + const records = element.querySelector("ol")!; + return { + bottom: cover.getBoundingClientRect().bottom, + records: records.getBoundingClientRect().top, + mask: getComputedStyle(image).maskImage, + filter: getComputedStyle(image).filter, + }; + }); + expect(preview.bottom).toBeLessThanOrEqual(preview.records); + expect(preview.mask).toBe("none"); + expect(preview.filter).toBe("none"); +}); + +test("map hover stays still and the preview opens the map", async ({ + page, +}) => { + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await card.scrollIntoViewIfNeeded(); + const before = await card.boundingBox(); + const border = await card.evaluate( + (element) => getComputedStyle(element).borderColor, + ); + await card.hover(); + expect(await card.boundingBox()).toEqual(before); + expect( + await card.evaluate((element) => getComputedStyle(element).borderColor), + ).not.toBe(border); + const href = await card.locator("h3 a").getAttribute("href"); + const preview = await card.locator(":scope > div").first().boundingBox(); + await page.mouse.click( + preview!.x + preview!.width / 2, + preview!.y + preview!.height / 2, + ); + await expect(page).toHaveURL(new RegExp(`${href}$`)); +}); + +test("player links and replay controls work independently of the map link", async ({ + page, +}) => { + await page.goto("/maps"); + const card = page.locator("[data-map]").first(); + await expect(card).toBeVisible(); + await page.evaluate(() => { + (window as { mapsStillHere?: boolean }).mapsStillHere = true; + }); + const replay = card + .getByRole("link", { name: "Watch replay", exact: true }) + .first(); + const href = await replay.getAttribute("href"); + const id = /\/runs\/(\d+)/.exec(href!)![1]; + await replay.click(); + await expect(page).toHaveURL(new RegExp(`/maps\\?replay=${id}$`)); + const dialog = page.getByRole("dialog"); + await expect(dialog).toBeVisible(); + await expect(dialog.getByRole("link", { name: "Run page" })).toHaveAttribute( + "href", + `/runs/${id}`, + ); + expect( + await page.evaluate( + () => (window as { mapsStillHere?: boolean }).mapsStillHere, + ), + ).toBe(true); + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(page).toHaveURL(/\/maps$/); + await expect(replay).toBeFocused(); + const player = card + .locator("ol > li") + .first() + .locator('a[href^="/players/"]'); + await expect( + card.locator("ol > li").first().locator('a[href^="/players/"]'), + ).toHaveCount(1); + const profile = await player.getAttribute("href"); + const avatar = player.locator(":scope > span").first(); + const name = player.locator(":scope > span").nth(1); + const color = await name.evaluate( + (element) => getComputedStyle(element).color, + ); + const avatarBorder = await avatar + .locator("img, span") + .first() + .evaluate((element) => getComputedStyle(element).borderColor); + await avatar.hover(); + await expect + .poll(() => name.evaluate((element) => getComputedStyle(element).color)) + .not.toBe(color); + expect( + await avatar + .locator("img, span") + .first() + .evaluate((element) => getComputedStyle(element).borderColor), + ).toBe(avatarBorder); + await avatar.click(); + await expect(page).toHaveURL(new RegExp(`${profile}$`)); + await page.goBack(); + await player.locator(":scope > span").nth(1).click(); + await expect(page).toHaveURL(new RegExp(`${profile}$`)); + await expect(dialog).toBeHidden(); }); test("cards keep complete names and long times inside at every breakpoint", async ({ @@ -68,17 +173,18 @@ test("cards keep complete names and long times inside at every breakpoint", asyn await expect(card).toBeVisible(); await page.evaluate(() => document.fonts.ready); await card.evaluate((element) => { - element.querySelector("h3")!.textContent = + element.querySelector("h3 a")!.textContent = "bhop_" + "long_map_name_".repeat(5).slice(0, 59); for (const row of Array.from(element.querySelectorAll("ol > li"))) { - const player = row.children[2]!; - const result = row.children[3]!; - player.textContent = "Long player name 玩家 日本語 Кириллица"; - result.children[0]!.textContent = "1:23:45.678"; + const player = row.querySelector('a[href^="/players/"]')!; + const result = row.lastElementChild!; + player.children[1]!.textContent = + "Long player name 玩家 日本語 Кириллица"; + result.children[0]!.querySelector("a")!.textContent = "1:23:45.678"; result.children[1]!.textContent = "+2:34:56.789"; } }); - for (const width of [1440, 1084, 1080, 1024, 768, 390, 320]) { + for (const width of [1920, 1440, 1084, 1080, 1024, 768, 390, 320]) { await page.setViewportSize({ width, height: 1000 }); await expectTextInside(card); expect( @@ -93,14 +199,24 @@ test("cards keep complete names and long times inside at every breakpoint", asyn ).display, })); expect(layout.result).toBe(layout.width >= 320 ? "grid" : "flex"); + if (width === 1920 || width === 1440) { + const columns = await card + .locator("xpath=../..") + .evaluate( + (element) => + getComputedStyle(element).gridTemplateColumns.split(" ").length, + ); + expect(columns).toBe(width === 1920 ? 4 : 3); + } } }); test("loading avatars and map pictures does not move the podium", async ({ page, }) => { - await page.route(/avatars\.(?:akamai\.)?steamstatic\.com/, (route) => - route.abort(), + await page.route( + /avatars(?:\.[a-z]+)?\.steamstatic\.com|\/v1\/players\/[^/]+\/avatar/, + (route) => route.abort(), ); await page.goto("/maps"); const card = page.locator("[data-map]").first(); @@ -125,22 +241,37 @@ test("a single finisher and an empty style stay honest and readable", async ({ page, request, }) => { - const response = await request.get("/v1/maps?style=scroll&limit=100"); - const list = (await response.json()) as Schemas["MapList"]; - test.skip(list.style !== "scroll", "The API has no Scroll style."); - const empty = list.maps.find((map) => !map.world_record); - test.skip(!empty, "The current API data has no empty Scroll board."); + let selected: { list: Schemas["MapList"]; style: string } | undefined; + for (const style of ["scroll", "hsw"]) { + const response = await request.get(`/v1/maps?style=${style}&limit=100`); + if (!response.ok()) continue; + const list = (await response.json()) as Schemas["MapList"]; + if ( + list.style === style && + list.maps.some((map) => !map.world_record) && + list.maps.some((map) => map.world_record) + ) { + selected = { list, style }; + break; + } + } + test.skip( + !selected, + "The current API data has no style with both empty and populated boards.", + ); + const { list, style } = selected!; + const empty = list.maps.find((map) => !map.world_record)!; await page.setViewportSize({ width: 390, height: 900 }); - await page.goto(`/maps?style=scroll&q=${encodeURIComponent(empty!.name)}`); + await page.goto(`/maps?style=${style}&q=${encodeURIComponent(empty.name)}`); const emptyCard = page.locator(`[data-map="${empty!.name}"]`); await expect( emptyCard.getByText("No times in this style", { exact: true }), ).toBeVisible(); await expect(emptyCard.getByLabel("Placement 1")).toHaveCount(0); await expectTextInside(emptyCard); - await expect(emptyCard).toHaveAttribute( + await expect(emptyCard.locator("h3 a")).toHaveAttribute( "href", - `/maps/${empty!.name}?style=scroll`, + `/maps/${empty.name}?style=${style}`, ); // Pick an actual sparse board rather than inventing second and third place. @@ -150,7 +281,7 @@ test("a single finisher and an empty style stay honest and readable", async ({ .sort((a, b) => a.players - b.players) .slice(0, 6)) { const response = await request.get( - `/v1/maps/${encodeURIComponent(map.name)}/leaderboard?style=scroll&limit=3`, + `/v1/maps/${encodeURIComponent(map.name)}/leaderboard?style=${style}&limit=3`, ); const board = (await response.json()) as Schemas["Leaderboard"]; if (board.total === 1) { @@ -160,13 +291,14 @@ test("a single finisher and an empty style stay honest and readable", async ({ } test.skip( !single, - "The current API data has no sampled Scroll board with one finisher.", + "The current API data has no sampled board with one finisher.", ); - await page.goto(`/maps?style=scroll&q=${encodeURIComponent(single!)}`); + await page.goto(`/maps?style=${style}&q=${encodeURIComponent(single!)}`); const singleCard = page.locator(`[data-map="${single}"]`); - await expect( - singleCard.getByText("1 ranked time in this style", { exact: true }), - ).toBeVisible(); + await expect(singleCard.locator("ol > li")).toHaveCount(1); + await expect(singleCard.getByText(/ranked times? in this style/)).toHaveCount( + 0, + ); await expect(singleCard.getByLabel("Placement 1")).toBeVisible(); await expect(singleCard.getByLabel("Placement 2")).toHaveCount(0); await expectTextInside(singleCard); diff --git a/web/e2e/maps-overview.e2e.ts b/web/e2e/maps-overview.e2e.ts index 1084cf4..5529378 100644 --- a/web/e2e/maps-overview.e2e.ts +++ b/web/e2e/maps-overview.e2e.ts @@ -22,17 +22,12 @@ async function expectAligned(overview: Locator) { headings: Array.from(element.querySelectorAll("section h2")).map( (heading) => heading.getBoundingClientRect().top, ), - lists: Array.from(element.querySelectorAll("section > div")).map( - (group) => - Math.abs(center(group.getBoundingClientRect()) - center(panel)), - ), }; }); expect(geometry.left).toBeLessThan(1); expect(geometry.right).toBeLessThan(1); expect(geometry.graph).toBeLessThan(1); expect(geometry.legend).toBeLessThan(1); - for (const offset of geometry.lists) expect(offset).toBeLessThan(1); for (const top of geometry.headings) { expect(Math.abs(top - geometry.headings[0]!)).toBeLessThan(1); } @@ -71,6 +66,144 @@ test("the overview stays centered and the reset matches the tier columns", async await reset.click(); await expect(reset).toHaveAttribute("aria-current", "true"); await expectAligned(overview); + + await page.setViewportSize({ width: 1920, height: 1000 }); + const spacing = await overview.evaluate((element) => { + const groups = Array.from(element.querySelectorAll("section")); + return { + trailing: + element.getBoundingClientRect().right - + groups[groups.length - 1]!.getBoundingClientRect().right, + columnGaps: groups.map( + (group) => + group.getBoundingClientRect().right - + (group.querySelector("ul") ?? group).getBoundingClientRect().right, + ), + }; + }); + expect(spacing.trailing).toBeLessThanOrEqual(21); + for (const gap of spacing.columnGaps) expect(gap).toBeLessThan(1); + const controls = await overview.locator("xpath=../..").evaluate((element) => { + const frame = element + .querySelector('[aria-label="Map overview"]')! + .parentElement!.getBoundingClientRect(); + const input = element + .querySelector('input[type="search"]')! + .getBoundingClientRect(); + const buttons = element.querySelectorAll('button[aria-haspopup="menu"]'); + const first = buttons[0]!.getBoundingClientRect(); + const gallery = document + .querySelector("[data-map]")! + .closest("section")! + .getBoundingClientRect(); + return { + searchWidth: input.width, + left: Math.abs(first.left - gallery.left), + right: Math.abs(input.right - gallery.right), + separated: input.top - frame.bottom, + frameCenter: Math.abs( + (frame.left + frame.right - gallery.left - gallery.right) / 2, + ), + frameWidth: frame.width, + pageWidth: gallery.width, + }; + }); + expect(controls.searchWidth).toBeLessThanOrEqual(320); + expect(controls.left).toBeLessThan(1); + expect(controls.right).toBeLessThan(1); + expect(controls.separated).toBeGreaterThanOrEqual(20); + expect(controls.frameCenter).toBeLessThan(1); + expect(controls.frameWidth).toBeLessThan(controls.pageWidth); +}); + +test("the donut has clean sector boundaries, animates hover and has no click focus box", async ({ + page, +}) => { + await page.emulateMedia({ reducedMotion: "no-preference" }); + await page.goto("/maps"); + const chart = page.getByRole("img", { name: /Maps per tier/ }); + await expect(chart).toBeVisible(); + const geometry = await chart.evaluate((svg) => { + const rect = svg.getBoundingClientRect(); + const reset = svg.parentElement!.querySelector("nav > a")!.textContent!; + const total = Number(reset.match(/([\d,]+) maps/)![1]!.replaceAll(",", "")); + const links = Array.from(svg.querySelectorAll("a")); + const count = Number( + links[0]! + .getAttribute("aria-label")! + .match(/: ([\d,]+) maps/)![1]! + .replaceAll(",", ""), + ); + const angle = (((((count / total) * 100) / 2) * 3.6 - 90) * Math.PI) / 180; + const hit = (share: number, radius: number) => { + const angle = (share / 100) * Math.PI * 2 - Math.PI / 2; + return ( + document + .elementFromPoint( + rect.x + rect.width * (0.5 + (radius / 100) * Math.cos(angle)), + rect.y + rect.height * (0.5 + (radius / 100) * Math.sin(angle)), + ) + ?.closest("svg a") + ?.getAttribute("aria-label") ?? null + ); + }; + let start = 0; + const samples = links.map((link) => { + const label = link.getAttribute("aria-label")!; + const count = Number( + label.match(/: ([\d,]+) maps/)![1]!.replaceAll(",", ""), + ); + const length = (count / total) * 100; + const sample = { + label, + middle: [33, 40, 47].map((radius) => hit(start + length / 2, radius)), + seam: + length === 100 + ? [] + : [33, 40, 47].map((radius) => hit(start, radius)), + }; + start += length; + return sample; + }); + return { + samples, + x: rect.x + rect.width * (0.5 + 0.4 * Math.cos(angle)), + y: rect.y + rect.height * (0.5 + 0.4 * Math.sin(angle)), + }; + }); + for (const sample of geometry.samples) { + for (const middle of sample.middle) expect(middle).toBe(sample.label); + for (const seam of sample.seam) expect(seam).toBeNull(); + } + const highlight = chart.locator("a").first().locator("path").last(); + await expect(highlight).toHaveCSS("opacity", "0"); + await page.mouse.move(geometry.x, geometry.y); + const hovered = await chart + .locator("a") + .first() + .locator("path") + .last() + .evaluate(async (path) => { + await Promise.all( + path.getAnimations().map((animation) => animation.finished), + ); + const style = getComputedStyle(path); + return { + transition: style.transitionProperty, + duration: parseFloat(style.transitionDuration), + }; + }); + await expect(highlight).toHaveCSS("opacity", "1"); + expect(hovered.transition).toContain("opacity"); + expect(hovered.duration).toBeGreaterThan(0); + await page.mouse.click(geometry.x, geometry.y); + await expect(chart.locator("text").first()).not.toHaveText("All"); + expect( + await chart + .locator("a") + .first() + .evaluate((link) => getComputedStyle(link).outlineStyle), + ).toBe("none"); }); test("a filtered short list is centered and its details stay beside the names", async ({ @@ -131,27 +264,22 @@ test("a filtered short list is centered and its details stay beside the names", ).toBeLessThan(1); const list = overview.locator("section:has(ul)").first().locator("ul"); await expect(list).toHaveCount(1); - const layout = await list.evaluate((element) => { - const rows = Array.from(element.querySelectorAll("a")); - return { - width: element.getBoundingClientRect().width, - details: rows.map( - (row) => row.lastElementChild!.getBoundingClientRect().left, - ), - gaps: rows.map((row) => { - const name = row.children[1]!; - const detail = row.children[2]!; - return ( - detail.getBoundingClientRect().left - - name.getBoundingClientRect().right - ); - }), - }; - }); - expect(layout.width).toBeLessThan(400); - for (const left of layout.details) - expect(Math.abs(left - layout.details[0]!)).toBeLessThan(1); - for (const gap of layout.gaps) expect(gap).toBe(8); + const layout = await list.evaluate((element) => + Array.from(element.querySelectorAll("a")).map((row) => { + const name = row.children[1]!.getBoundingClientRect(); + const detail = row.children[2]!.getBoundingClientRect(); + return { + width: row.getBoundingClientRect().width, + gap: detail.left - name.right, + top: Math.abs(detail.top - name.top), + }; + }), + ); + for (const row of layout) { + expect(row.width).toBeLessThan(250); + expect(Math.abs(row.gap - 8)).toBeLessThan(1); + expect(row.top).toBeLessThan(1); + } }); test("the compact legend fits a narrow phone without changing its reset alignment", async ({ @@ -178,3 +306,37 @@ test("the compact legend fits a narrow phone without changing its reset alignmen expect(Math.abs(edges.right)).toBeLessThan(1); expect(edges.overflow).toBe(false); }); + +test("searching a WR holder shows their maps", async ({ page, request }) => { + const response = await request.get("/v1/maps?limit=100"); + expect(response.ok()).toBe(true); + const all = (await response.json()) as Schemas["MapList"]; + const holder = all.maps.find((map) => map.world_record)?.world_record?.player + .name; + test.skip( + !holder, + "The current data has no world record holders to search for.", + ); + const matches = await request.get( + `/v1/maps?q=${encodeURIComponent(holder!)}&sort=popular`, + ); + expect(matches.ok()).toBe(true); + const filtered = (await matches.json()) as Schemas["MapList"]; + expect(filtered.total).toBeGreaterThan(0); + + await page.goto("/maps"); + await page + .getByRole("searchbox", { + name: "Search maps, WR holders, or enter a SteamID", + exact: true, + }) + .fill(holder!); + await expect(page).toHaveURL((url) => url.searchParams.get("q") === holder); + const cards = page.locator("[data-map]"); + await expect(cards).toHaveCount(filtered.maps.length); + expect( + await cards.evaluateAll((elements) => + elements.map((element) => element.getAttribute("data-map")), + ), + ).toEqual(filtered.maps.map((map) => map.name)); +}); diff --git a/web/src/api/schema.ts b/web/src/api/schema.ts index 81060d7..a6b0e3b 100644 --- a/web/src/api/schema.ts +++ b/web/src/api/schema.ts @@ -3962,9 +3962,9 @@ export interface operations { parameters: { query?: { /** - * @description Part of a map name. Case doesn't matter, and spaces stand for underscores. The map of exactly that - * name comes first, then maps with a word starting with it, then other matches, each in the chosen - * sort; near misses for a typo come last, closest first. + * @description Part of a map name or a main-track world record holder's name in the chosen style. Case doesn't + * matter; spaces in map names stand for underscores. Exact map names come first, then word starts, + * other map matches and record holders, each in the chosen sort; near misses come last. */ q?: string | null; /** @description Default `name`. */ diff --git a/web/src/features/maps/MapCard.module.css b/web/src/features/maps/MapCard.module.css index f42f68f..803e6f2 100644 --- a/web/src/features/maps/MapCard.module.css +++ b/web/src/features/maps/MapCard.module.css @@ -1,16 +1,26 @@ /* Shared podium columns switch with the card's width, not the viewport's. */ -.picture { - mask-image: linear-gradient(to right, black 40%, transparent 60%); -} - .cards { grid-template-columns: minmax(0, 1fr); } +.cover { + aspect-ratio: 5 / 2; + min-block-size: calc(var(--spacing) * 32); +} + +.preview { + transition: filter var(--duration-fast); +} + +@media (prefers-reduced-motion: reduce) { + .preview { + transition: none; + } +} + .podium { align-content: start; grid-template-columns: auto auto minmax(0, 1fr); - min-block-size: calc(var(--spacing) * 38); } .entry { @@ -21,16 +31,23 @@ .rank { grid-column: 1; - grid-row: 1 / span 2; + grid-row: 1; +} + +.playerLink { + grid-column: 2 / -1; + grid-row: 1; + grid-template-columns: subgrid; } .avatar { - grid-column: 2; - grid-row: 1 / span 2; + grid-column: 1; + grid-row: 1; + align-self: center; } .player { - grid-column: 3; + grid-column: 2; grid-row: 1; } @@ -39,27 +56,25 @@ grid-row: 2; } -/* Intrinsic name and time columns stay together instead of filling the card with blank space. */ +/* Wide cards share aligned time and gap columns; narrow cards put both below the name. */ @container (min-width: 20rem) { .podium { grid-template-columns: - auto auto minmax(0, max-content) + auto auto minmax(0, 1fr) max-content max-content; - min-block-size: calc(var(--spacing) * 26); } .entry { min-block-size: calc(var(--spacing) * 8); } - .player, + .playerLink, .result { align-self: center; } - .rank, - .avatar { - grid-row: 1; + .playerLink { + grid-column: 2 / span 2; } .result { diff --git a/web/src/features/maps/MapCard.tsx b/web/src/features/maps/MapCard.tsx index 2196dec..d6365b5 100644 --- a/web/src/features/maps/MapCard.tsx +++ b/web/src/features/maps/MapCard.tsx @@ -1,6 +1,8 @@ -// A map preview with its main-track top three; names wrap and numeric columns stay aligned. +// Map details overlay the preview; records and the signed-in player's PB sit plainly below it. import type { Schemas } from "@/api/client"; import { avatarSrc } from "@/features/players/avatarSrc"; +import { ReplayLink } from "@/features/replays/ReplayLink"; +import { RunLink } from "@/features/runs/RunLink"; import { formatGap, formatTime } from "@/features/runs/time"; import { Avatar } from "@/ui/Avatar"; import { Badge } from "@/ui/Badge"; @@ -20,12 +22,16 @@ export function MapCard({ leaders, styleName, styleKey, + showPersonalBest = false, + personalBest, }: { map: Schemas["MapSummary"]; tierCount: number | null | undefined; leaders: readonly MapLeader[] | null; styleName: string; styleKey?: string; + showPersonalBest?: boolean; + personalBest?: MapLeader | null; }) { const entries = leaders ?? (map.world_record ? [{ ...map.world_record, rank: 1 }] : []); @@ -33,51 +39,58 @@ export function MapCard({ const fastest = record?.time ?? 0; return ( -
- -
-
-
- {map.tier != null && tierCount != null && ( - - - + - {map.name} - -
-

- - {number.format(map.players)}{" "} - {map.players === 1 ? "player" : "players"} - - {map.bonuses > 0 && ( + /> +

+
+ {map.tier != null && tierCount != null && ( + + + + )} +

+ + {map.name} + +

+
+

- {number.format(map.bonuses)}{" "} - {map.bonuses === 1 ? "bonus" : "bonuses"} + {number.format(map.players)}{" "} + {map.players === 1 ? "player" : "players"} - )} -

+ {map.bonuses > 0 && ( + + {number.format(map.bonuses)}{" "} + {map.bonuses === 1 ? "bonus" : "bonuses"} + + )} +

+
-
+
    {entries.map((entry) => (
  1. - - - - - {entry.player.name} - + + + + + {entry.player.name} + + - - {formatTime(entry.time)} + + + {formatTime(entry.time)} + + {entry.run_id === record?.run_id ? ( ))} {entries.length === 0 && ( -
  2. - No times in this style -
  3. - )} - {entries.length > 0 && entries.length < 3 && ( -
  4. - {leaders == null - ? "Top 3 couldn't be loaded" - : `${entries.length} ${entries.length === 1 ? "ranked time" : "ranked times"} in this style`} +
  5. + {leaders === null + ? "Times couldn't be loaded" + : "No times in this style"}
  6. )}
+ {showPersonalBest && ( +
+ Your PB + {personalBest ? ( + <> + + #{number.format(personalBest.rank)} + + + + {formatTime(personalBest.time)} + + {personalBest.time > fastest && fastest > 0 ? ( + + ({formatGap(personalBest.time - fastest)}) + + ) : fastest > 0 ? ( + + {personalBest.run_id === record?.run_id ? "WR" : "WR tie"} + + ) : null} + + + ) : ( + + {personalBest === null ? "Not completed" : "Couldn't load PB"} + + )} +
+ )}
- + ); } diff --git a/web/src/features/maps/MapImage.tsx b/web/src/features/maps/MapImage.tsx index 33cf84d..71719cd 100644 --- a/web/src/features/maps/MapImage.tsx +++ b/web/src/features/maps/MapImage.tsx @@ -8,7 +8,7 @@ import { classNames } from "@/ui/classNames"; const sizes = { thumbnail: "h-10 w-14 rounded-md sm:h-12 sm:w-20", tile: "h-14 w-24 rounded-md sm:h-20 sm:w-36", - card: "h-full w-full rounded-none border-0", + card: "aspect-video w-full rounded-none border-0", banner: "h-36 w-full rounded-md lg:h-44", }; @@ -51,9 +51,7 @@ export function MapImage({ "text-text-subtle flex items-center justify-center", )} > - {size !== "card" && ( - - )} + ); } diff --git a/web/src/features/maps/MapList.tsx b/web/src/features/maps/MapList.tsx index 1746878..d1102a7 100644 --- a/web/src/features/maps/MapList.tsx +++ b/web/src/features/maps/MapList.tsx @@ -26,6 +26,7 @@ import { managesMaps } from "./MapHeader"; import { MapCard } from "./MapCard"; import { mapPodiums } from "./mapPodiums"; import cardStyles from "./MapCard.module.css"; +import overviewStyles from "./MapOverview.module.css"; import { MAP_NAME } from "./mapName"; import { tierParam } from "./tierParam"; import { avatarSrc } from "@/features/players/avatarSrc"; @@ -153,7 +154,7 @@ export async function MapList({ params }: { params: MapListParams }) { .catch(() => undefined); const list = result?.data; const style = list?.style ?? requestedStyle; - const podiums = await mapPodiums(list?.maps ?? [], style); + const podiums = await mapPodiums(list?.maps ?? [], style, me?.steamid64); const typedName = q.toLowerCase(); const offerSetUp = staff && @@ -210,25 +211,18 @@ export async function MapList({ params }: { params: MapListParams }) {

Maps

{list && ( - href({ tier: choice })} - newestHref={href({ sort: "newest", page: 1 })} - /> + + href({ tier: choice })} + newestHref={href({ sort: "newest", page: 1 })} + /> + )} -
- +
{!unplayed && ( <> @@ -276,6 +270,15 @@ export async function MapList({ params }: { params: MapListParams }) { {/* Staff only, out of the way of the menus everyone uses. */} {staff &&
{staffTabs}
}
+
{/* With no results, the empty card below offers this instead. */} @@ -303,7 +306,7 @@ export async function MapList({ params }: { params: MapListParams }) { : completion === "no" ? "This player has completed every map here." : q - ? "No map with a run has that name." + ? "No maps match that name or WR holder." : tier != null ? `No map with a run has tier ${tier}.` : "No map has a finished run yet."} @@ -345,7 +348,9 @@ export async function MapList({ params }: { params: MapListParams }) { 0; - const singleSummary = Number(newest.length > 0) + Number(hasWeekly) === 1; return ( - {hasTiers && ( -
+
)} - {newest.length > 0 && ( +
({ name: map.name, @@ -439,25 +440,24 @@ function MapStats({ }))} tierCount={tierCount} /> - )} - {hasWeekly && ( - ({ - name: map.name, - tier: map.tier, - detail: `${number.format(map.players)} ${map.players === 1 ? "player" : "players"}`, - }))} - tierCount={tierCount} - /> - )} - + {hasWeekly && ( + ({ + name: map.name, + tier: map.tier, + detail: `${number.format(map.players)} ${map.players === 1 ? "player" : "players"}`, + }))} + tierCount={tierCount} + /> + )} +
+
); } @@ -465,69 +465,61 @@ function MapStats({ function MapStatsList({ title, empty, - singleSummary, href, maps, tierCount, }: { title: string; empty?: string; - singleSummary: boolean; href?: string; maps: { name: string; tier?: number | null; detail: string }[]; tierCount: number | null | undefined; }) { return ( -
-
-

- {href ? ( - - {title} - - ) : ( - title - )} -

- {maps.length === 0 ? ( -

{empty}

+
+

+ {href ? ( + + {title} + ) : ( -
    - {maps.map((map) => ( -
  • - - {map.tier != null && tierCount != null ? ( - - ) : ( - - )} - - {map.name} - - - {map.detail} - - -
  • - ))} -
+ title )} -

+ + {maps.length === 0 ? ( +

{empty}

+ ) : ( +
    + {maps.map((map) => ( +
  • + + {map.tier != null && tierCount != null ? ( + + ) : ( + + )} + + {map.name} + + + {map.detail} + + +
  • + ))} +
+ )}
); } diff --git a/web/src/features/maps/MapOverview.module.css b/web/src/features/maps/MapOverview.module.css new file mode 100644 index 0000000..cf3e0b2 --- /dev/null +++ b/web/src/features/maps/MapOverview.module.css @@ -0,0 +1,160 @@ +/* A centered overview sits above the separate map controls; summary rows keep their details close. */ +.overview { + display: grid; + gap: calc(var(--spacing) * 4); + min-inline-size: 0; + max-inline-size: 80rem; + margin-inline: auto; +} + +.toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: calc(var(--spacing) * 3); + min-inline-size: 0; +} + +.search { + order: -1; + min-inline-size: 0; +} + +.search input { + border-color: var(--color-border-strong); + background-color: var(--color-bg); +} + +.search input:focus { + border-color: var(--color-accent); +} + +.summaries { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: calc(var(--spacing) * 4); + border-block-start: 1px solid var(--color-border); + padding-block-start: calc(var(--spacing) * 4); + min-inline-size: 0; +} + +.summary { + display: flex; + flex-direction: column; + gap: calc(var(--spacing) * 2); + min-inline-size: 0; +} + +.list { + display: grid; + gap: calc(var(--spacing) * 2); +} + +.link { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: start; + gap: 0 calc(var(--spacing) * 1.5); + min-block-size: calc(var(--spacing) * 10); +} + +.detail { + grid-column: 2; + grid-row: 2; + align-self: center; +} + +.link > :first-child { + grid-column: 1; + grid-row: 2; +} + +.link > :nth-child(2) { + grid-column: 1 / -1; + grid-row: 1; +} + +@media (min-width: 80rem) { + .overview { + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: calc(var(--spacing) * 6); + } + + .summaries { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: calc(var(--spacing) * 6); + border-block-start: 0; + border-inline-start: 1px solid var(--color-border); + padding-block-start: 0; + padding-inline-start: calc(var(--spacing) * 6); + } + + .summary { + gap: calc(var(--spacing) * 2); + min-block-size: calc(var(--spacing) * 44); + } + + .summary + .summary { + border-inline-start: 1px solid var(--color-border); + padding-inline-start: calc(var(--spacing) * 6); + } + + .summary h2 { + display: flex; + align-items: center; + min-block-size: calc(var(--spacing) * 8); + } + + .list { + grid-template-columns: auto auto auto; + justify-content: start; + gap: var(--spacing) calc(var(--spacing) * 2); + } + + .list > li, + .link { + display: grid; + grid-column: 1 / -1; + grid-template-columns: subgrid; + } + + .link { + align-items: center; + column-gap: calc(var(--spacing) * 2); + min-block-size: calc(var(--spacing) * 6); + } + + .link > :first-child, + .link > :nth-child(2), + .detail { + grid-row: 1; + } + + .link > :nth-child(2) { + grid-column: 2; + } + + .detail { + grid-column: 3; + text-align: end; + font-size: var(--text-sm); + line-height: var(--text-sm--line-height); + } +} + +@media (min-width: 48rem) { + .search { + order: 0; + inline-size: 20rem; + flex: none; + margin-inline-start: auto; + } +} + +.summaries:only-child { + grid-column: 1 / -1; + border: 0; + padding: 0; +} diff --git a/web/src/features/maps/mapPodiums.test.ts b/web/src/features/maps/mapPodiums.test.ts new file mode 100644 index 0000000..8f8e65c --- /dev/null +++ b/web/src/features/maps/mapPodiums.test.ts @@ -0,0 +1,82 @@ +// PBs use the selected style and viewer, and a failed lookup must not look like an uncompleted map. +import { beforeEach, expect, it, vi } from "vitest"; +import type { Schemas } from "../../api/client"; +import { mapPodiums } from "./mapPodiums"; + +const { get } = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock("next/cache", () => ({ cacheLife: vi.fn() })); +vi.mock("@/api/client", () => ({ api: { GET: get } })); + +const entry = { + rank: 5, + player: { name: "Runner", steamid64: "76561198000000001" }, + time: 12, + run_id: 73, +}; +const record = { + ...entry, + rank: 1, + time: 10, + run_id: 70, + player: { name: "Leader", steamid64: "76561198000000003" }, +}; +const map: Schemas["MapSummary"] = { + name: "bhop_test", + players: 10, + bonuses: 0, + last_run_at: "2026-11-09T00:00:00Z", + world_record: { ...record, finished_at: "2026-11-09T00:00:00Z" }, +}; + +beforeEach(() => { + get.mockReset(); +}); + +it("loads the viewer's PB in the same style-scoped request as the podium", async () => { + get.mockResolvedValue({ data: { entries: [record], player_entry: entry } }); + const result = await mapPodiums([map], "scroll", entry.player.steamid64); + expect(get).toHaveBeenCalledOnce(); + expect(get.mock.calls[0]![1].params.query).toEqual({ + style: "scroll", + track: 0, + limit: 3, + player: entry.player.steamid64, + }); + expect(result.get(map.name)?.personalBest).toEqual(entry); + expect(result.get(map.name)?.entries).toEqual([record]); +}); + +it("scopes each viewer independently and omits PBs for signed-out visitors", async () => { + get.mockImplementation(async (_path, options) => ({ + data: { + entries: [record], + player_entry: + options.params.query.player === entry.player.steamid64 ? entry : null, + }, + })); + expect( + (await mapPodiums([map], "normal", entry.player.steamid64)).get(map.name) + ?.personalBest, + ).toEqual(entry); + expect( + (await mapPodiums([map], "normal", "76561198000000002")).get(map.name) + ?.personalBest, + ).toBeNull(); + expect( + (await mapPodiums([map], "normal")).get(map.name)?.personalBest, + ).toBeUndefined(); +}); + +it("distinguishes an empty style from a failed request", async () => { + const empty = await mapPodiums( + [{ ...map, world_record: null }], + "normal", + entry.player.steamid64, + ); + expect(empty.get(map.name)?.personalBest).toBeNull(); + expect(get).not.toHaveBeenCalled(); + get.mockRejectedValue(new Error("unreachable")); + expect( + (await mapPodiums([map], "normal", entry.player.steamid64)).get(map.name), + ).toBeNull(); +}); diff --git a/web/src/features/maps/mapPodiums.ts b/web/src/features/maps/mapPodiums.ts index ae9a469..7a12672 100644 --- a/web/src/features/maps/mapPodiums.ts +++ b/web/src/features/maps/mapPodiums.ts @@ -1,4 +1,4 @@ -// Public main-track podiums for the map cards, cached briefly and fetched in bounded batches. +// Map-card podiums and the viewer's public PB, cached per style and player in bounded batches. import { cacheLife } from "next/cache"; import { api, type Schemas } from "@/api/client"; @@ -7,21 +7,32 @@ export type MapLeader = Pick< "rank" | "player" | "time" | "run_id" >; +export interface MapPodium { + entries: readonly MapLeader[]; + personalBest?: MapLeader | null; +} + export async function mapPodiums( maps: Schemas["MapSummary"][], style: string | null | undefined, -): Promise> { - const podiums = new Map(); + player?: string, +): Promise> { + const podiums = new Map(); if (!style) return podiums; // Avoid issuing a page's worth of independent requests to the beta API at once. for (let offset = 0; offset < maps.length; offset += 6) { const batch = await Promise.all( maps.slice(offset, offset + 6).map(async (map) => { - if (!map.world_record) return [map.name, []] as const; + if (!map.world_record) + return [ + map.name, + { entries: [], personalBest: player ? null : undefined }, + ] as const; const leaders = await cachedPodium({ map: map.name, style, record: map.world_record.run_id, + player, }).catch(() => null); return [map.name, leaders] as const; }), @@ -37,21 +48,26 @@ async function cachedPodium(key: { style: string; // A new WR changes the key, so cached cards cannot contradict the map list's winner. record: number; -}): Promise { + // PBs are public, but each viewer must have a separate cache entry. + player?: string; +}): Promise { "use cache"; cacheLife({ stale: 30, revalidate: 30, expire: 300 }); const { data, response } = await api.GET("/v1/maps/{map}/leaderboard", { params: { path: { map: key.map }, - query: { style: key.style, track: 0, limit: 3 }, + query: { style: key.style, track: 0, limit: 3, player: key.player }, }, signal: AbortSignal.timeout(5000), }); if (!data) throw new Error(`Map podium answered ${response.status}`); - return data.entries.map(({ rank, player, time, run_id }) => ({ - rank, - player, - time, - run_id, - })); + return { + entries: data.entries.map(({ rank, player, time, run_id }) => ({ + rank, + player, + time, + run_id, + })), + personalBest: key.player ? (data.player_entry ?? null) : undefined, + }; } diff --git a/web/src/ui/TierSpread.tsx b/web/src/ui/TierSpread.tsx index dede22a..b6ca166 100644 --- a/web/src/ui/TierSpread.tsx +++ b/web/src/ui/TierSpread.tsx @@ -11,9 +11,27 @@ const percent = new Intl.NumberFormat("en", { }); const number = new Intl.NumberFormat("en"); const RADIUS = 40; -const WIDTH = 14; +const WIDTH = 16; const GAP = 0.6; +// Filled sectors keep their angular boundaries when highlighted, unlike repeated stroke dashes. +function sector(start: number, length: number, width: number) { + const outer = RADIUS + width / 2; + const inner = RADIUS - width / 2; + const point = (share: number, radius: number) => { + const angle = (share / 100) * Math.PI * 2 - Math.PI / 2; + return `${50 + radius * Math.cos(angle)} ${50 + radius * Math.sin(angle)}`; + }; + if (length === 100) { + return `M ${point(start, outer)} A ${outer} ${outer} 0 1 1 ${point(start + 50, outer)} A ${outer} ${outer} 0 1 1 ${point(start, outer)} L ${point(start, inner)} A ${inner} ${inner} 0 1 0 ${point(start + 50, inner)} A ${inner} ${inner} 0 1 0 ${point(start, inner)} Z`; + } + const gap = Math.min(GAP, length / 3); + const from = start + gap / 2; + const to = start + length - gap / 2; + const large = to - from > 50 ? 1 : 0; + return `M ${point(from, outer)} A ${outer} ${outer} 0 ${large} 1 ${point(to, outer)} L ${point(to, inner)} A ${inner} ${inner} 0 ${large} 0 ${point(from, inner)} Z`; +} + export function TierSpread({ byTier, untiered, @@ -57,18 +75,11 @@ export function TierSpread({ aria-label={`Maps per tier, ${tierCount} tiers`} className="hidden size-40 shrink-0 sm:block" > - + {untiered > 0 && ( - )} {slices.map( @@ -79,25 +90,22 @@ export function TierSpread({ href={tierHref(selected === tier ? null : tier)} scroll={false} tabIndex={-1} + style={ + { "--tier": tierColor(tier, tierCount) } as CSSProperties + } + className={classNames( + "group/arc fill-(--tier) transition-opacity duration-(--duration-base) outline-none motion-reduce:transition-none", + !all && selected !== tier && "opacity-25", + )} aria-label={`Tier ${tier}: ${number.format(count)} maps`} > {`Tier ${tier}: ${number.format(count)} maps`} - + From deebea16592334c39be292051568b3189a02ad2d Mon Sep 17 00:00:00 2001 From: zasbu <136494048+zasbu@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:01:57 +1100 Subject: [PATCH 2/4] Keep Steam sign-in on one browser origin --- api/crates/api/src/auth.rs | 61 +++++++++++++++++++++++++++++ web/e2e/auth.e2e.ts | 36 +++++++++++++++++ web/src/app/sign-in/failed/page.tsx | 18 ++++++++- 3 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 web/e2e/auth.e2e.ts diff --git a/api/crates/api/src/auth.rs b/api/crates/api/src/auth.rs index df8b1a4..ab73adb 100644 --- a/api/crates/api/src/auth.rs +++ b/api/crates/api/src/auth.rs @@ -89,10 +89,30 @@ pub fn routes() -> OpenApiRouter { )] async fn start( State(state): State, + headers: HeaderMap, jar: CookieJar, Query(query): Query, ) -> (CookieJar, Redirect) { let return_to = ReturnTo::new(query.return_to.as_deref()); + // The cookie and Steam's callback must use the same host, including localhost's aliases. + let host = headers + .get("x-forwarded-host") + .or_else(|| headers.get("host")); + if let Some(host) = host.and_then(|value| value.to_str().ok()) { + let origin = url::Url::parse(&format!("{}://{host}", state.public_url.scheme())) + .ok() + .map(|url| url.origin()); + if origin != Some(state.public_url.origin()) { + let mut start = state + .public_url + .join("/v1/auth/steam") + .expect("a valid path"); + start + .query_pairs_mut() + .append_pair("return_to", return_to.as_str()); + return (jar, Redirect::to(start.as_str())); + } + } // A sign-in started in another tab since replaces this value, so only the latest one completes. let browser = sessions::generate(); let login_url = openid::login_url(&state.steam, &state.public_url, &return_to, &browser); @@ -481,6 +501,47 @@ mod tests { let _: ErrorBody = again.json(); } + #[sqlx::test] + async fn sign_in_uses_its_callback_origin_before_setting_the_cookie(db: PgPool) { + let state = state(&db, fake_steam(true).await); + let response = test_client::send_to( + state.clone(), + Request::get("/v1/auth/steam?return_to=%2Fmaps%3Ftier%3D2") + .header(header::HOST, "127.0.0.1:8080") + .header("x-forwarded-host", "127.0.0.1:3000") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(response.status, 303); + let destination = Url::parse(response.headers[header::LOCATION].to_str().unwrap()).unwrap(); + assert_eq!(destination.origin(), state.public_url.origin()); + assert_eq!(destination.path(), "/v1/auth/steam"); + assert_eq!( + destination.query_pairs().collect::>(), + [("return_to".into(), "/maps?tier=2".into())] + ); + assert!(set_cookie(&response, SIGN_IN_COOKIE).is_none()); + + let response = test_client::send_to( + state.clone(), + Request::get("/v1/auth/steam?return_to=%2Fmaps%3Ftier%3D2") + .header(header::HOST, "127.0.0.1:8080") + .header("x-forwarded-host", "sourcejump.test") + .body(Body::empty()) + .unwrap(), + ) + .await; + assert_eq!(response.status, 303); + assert!( + response.headers[header::LOCATION] + .to_str() + .unwrap() + .starts_with(state.steam.openid_endpoint.as_str()) + ); + assert!(set_cookie(&response, SIGN_IN_COOKIE).is_some()); + } + #[sqlx::test] async fn start_sends_the_browser_to_steam(db: PgPool) { let response = test_client::get(&db, "/v1/auth/steam?return_to=//evil.example").await; diff --git a/web/e2e/auth.e2e.ts b/web/e2e/auth.e2e.ts new file mode 100644 index 0000000..299a9af --- /dev/null +++ b/web/e2e/auth.e2e.ts @@ -0,0 +1,36 @@ +// Sign-in uses one browser origin and only shows failure text for signed-out visitors. +import { expect, test } from "@playwright/test"; + +test("sign-in canonicalizes a localhost alias before issuing its browser cookie", async ({ + request, +}) => { + const alias = await request.get( + "http://127.0.0.1:3000/v1/auth/steam?return_to=%2Fmaps%3Ftier%3D2", + { maxRedirects: 0 }, + ); + expect(alias.status()).toBe(303); + expect(alias.headers()["set-cookie"]).toBeUndefined(); + const canonical = new URL(alias.headers().location!); + expect(canonical.hostname).toBe("localhost"); + expect(canonical.searchParams.get("return_to")).toBe("/maps?tier=2"); + const start = await request.get(canonical.href, { maxRedirects: 0 }); + expect(start.status()).toBe(303); + expect(start.headers()["set-cookie"]).toContain("sj_sign_in="); + const steam = new URL(start.headers().location!); + expect(steam.hostname).toBe("steamcommunity.com"); + const callback = new URL(steam.searchParams.get("openid.return_to")!); + expect(callback.origin).toBe(canonical.origin); + expect(callback.searchParams.get("return_to")).toBe("/maps?tier=2"); +}); + +test("a signed-out visitor still sees the sign-in failure message", async ({ + page, +}) => { + await page.goto("/sign-in/failed"); + await expect( + page.getByRole("heading", { name: "Sign-in didn't complete" }), + ).toBeVisible(); + await expect( + page.getByRole("main").getByRole("link", { name: "Sign in with Steam" }), + ).toBeVisible(); +}); diff --git a/web/src/app/sign-in/failed/page.tsx b/web/src/app/sign-in/failed/page.tsx index 1ffcb72..ca3582b 100644 --- a/web/src/app/sign-in/failed/page.tsx +++ b/web/src/app/sign-in/failed/page.tsx @@ -1,5 +1,8 @@ -// Where sign-in lands when Steam didn't confirm it. +// Show a sign-in failure only when the request has no valid session. import type { Metadata } from "next"; +import { Suspense } from "react"; +import { redirect } from "next/navigation"; +import { signedInPlayer } from "@/features/auth/signedInPlayer"; import { Page } from "@/ui/Page"; import { SteamButton } from "@/ui/SteamButton"; @@ -11,12 +14,23 @@ export const metadata: Metadata = { export default function SignInFailedPage() { return ( + + + + + ); +} + +async function FailureContent() { + if (await signedInPlayer()) redirect("/"); + return ( + <>

Sign-in didn't complete

Steam didn't confirm the sign-in, or it took too long. Nothing was changed. Try again.

Sign in with Steam - + ); } From f77baefac38a540a200b9bed18043ca931f410b9 Mon Sep 17 00:00:00 2001 From: zasbu <136494048+zasbu@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:02:02 +1100 Subject: [PATCH 3/4] Proxy beta replay assets during local development --- web/next.config.ts | 8 ++++++- web/src/features/replays/ReplayPlayer.tsx | 9 +++---- web/src/features/replays/assetUrl.test.ts | 29 +++++++++++++++++++++++ web/src/features/replays/assetUrl.ts | 8 +++++++ 4 files changed, 49 insertions(+), 5 deletions(-) create mode 100644 web/src/features/replays/assetUrl.test.ts create mode 100644 web/src/features/replays/assetUrl.ts diff --git a/web/next.config.ts b/web/next.config.ts index 4ca998d..34d27c9 100644 --- a/web/next.config.ts +++ b/web/next.config.ts @@ -17,7 +17,13 @@ const nextConfig: NextConfig = { async rewrites() { if (process.env.NODE_ENV !== "development") return []; const api = process.env.SJ_API_URL ?? "http://127.0.0.1:8080"; - return [{ source: "/v1/:path*", destination: `${api}/v1/:path*` }]; + return [ + { source: "/v1/:path*", destination: `${api}/v1/:path*` }, + { + source: "/_beta-files/:path*", + destination: "https://files.sourcejump.net/:path*", + }, + ]; }, experimental: { // That proxying buffers request bodies, cut off at 10 MB by default; a packed map can be up to the API's diff --git a/web/src/features/replays/ReplayPlayer.tsx b/web/src/features/replays/ReplayPlayer.tsx index 26d9823..31e8557 100644 --- a/web/src/features/replays/ReplayPlayer.tsx +++ b/web/src/features/replays/ReplayPlayer.tsx @@ -22,6 +22,7 @@ import { findComparison, } from "./comparison"; import { REPLAY_ANCHOR } from "./anchor"; +import { replayAssetUrl } from "./assetUrl"; import { ComparisonLegend } from "./ComparisonLegend"; import { storedOverlays, storeOverlays } from "./overlays"; import { type ControlsHandle, ReplayControls } from "./ReplayControls"; @@ -161,9 +162,9 @@ export function ReplayPlayer({ canvas, { mapName: run.map, - mapUrl: map.viewer_file.url, - stockContentUrl: map.viewer_file.stock_content_url, - replayUrl, + mapUrl: replayAssetUrl(map.viewer_file.url), + stockContentUrl: replayAssetUrl(map.viewer_file.stock_content_url), + replayUrl: replayAssetUrl(replayUrl), }, { onFrame: (state, timer, compared, viewed) => { @@ -484,6 +485,6 @@ async function loadComparison( ): Promise { const found = await findComparison(run, runId, signal); if (typeof found === "string") return found; - await session.compareWith(found.replayUrl, signal); + await session.compareWith(replayAssetUrl(found.replayUrl), signal); return found.comparison; } diff --git a/web/src/features/replays/assetUrl.test.ts b/web/src/features/replays/assetUrl.test.ts new file mode 100644 index 0000000..a9fd4eb --- /dev/null +++ b/web/src/features/replays/assetUrl.test.ts @@ -0,0 +1,29 @@ +// Local beta playback must proxy only the public file host and leave deployed asset URLs alone. +import { afterEach, expect, it, vi } from "vitest"; +import { replayAssetUrl } from "./assetUrl"; + +afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); +}); + +it("proxies beta assets locally, preserving paths and queries", () => { + vi.stubEnv("NODE_ENV", "development"); + vi.stubGlobal("window", { location: { origin: "http://localhost:3000" } }); + expect(replayAssetUrl("https://files.sourcejump.net/stock/css-v1/?v=2")).toBe( + "http://localhost:3000/_beta-files/stock/css-v1/?v=2", + ); + expect(replayAssetUrl("http://localhost:3900/maps/test.bsp")).toBe( + "http://localhost:3900/maps/test.bsp", + ); + expect( + replayAssetUrl("https://files.sourcejump.net.example.com/run.sjr"), + ).toBe("https://files.sourcejump.net.example.com/run.sjr"); +}); + +it("keeps deployed playback direct", () => { + vi.stubEnv("NODE_ENV", "production"); + expect(replayAssetUrl("https://files.sourcejump.net/replays/test.sjr")).toBe( + "https://files.sourcejump.net/replays/test.sjr", + ); +}); diff --git a/web/src/features/replays/assetUrl.ts b/web/src/features/replays/assetUrl.ts new file mode 100644 index 0000000..1d7f587 --- /dev/null +++ b/web/src/features/replays/assetUrl.ts @@ -0,0 +1,8 @@ +// Beta's bucket permits the beta origin, so local development proxies public viewer files through Next. +export function replayAssetUrl(url: string): string { + if (process.env.NODE_ENV !== "development") return url; + const file = new URL(url); + return file.origin === "https://files.sourcejump.net" + ? `${window.location.origin}/_beta-files${file.pathname}${file.search}` + : url; +} From e2c38fba8e898266d5cbca34b10032643cd0d17d Mon Sep 17 00:00:00 2001 From: zasbu <136494048+zasbu@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:02:08 +1100 Subject: [PATCH 4/4] Align mobile map search with the filter row --- web/e2e/maps-cards.e2e.ts | 6 ++++++ web/src/features/maps/MapOverview.module.css | 10 +++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/web/e2e/maps-cards.e2e.ts b/web/e2e/maps-cards.e2e.ts index f600667..e1d6398 100644 --- a/web/e2e/maps-cards.e2e.ts +++ b/web/e2e/maps-cards.e2e.ts @@ -186,6 +186,12 @@ test("cards keep complete names and long times inside at every breakpoint", asyn }); for (const width of [1920, 1440, 1084, 1080, 1024, 768, 390, 320]) { await page.setViewportSize({ width, height: 1000 }); + await page.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ), + ); await expectTextInside(card); expect( await page.evaluate( diff --git a/web/src/features/maps/MapOverview.module.css b/web/src/features/maps/MapOverview.module.css index cf3e0b2..86ad065 100644 --- a/web/src/features/maps/MapOverview.module.css +++ b/web/src/features/maps/MapOverview.module.css @@ -8,7 +8,10 @@ } .toolbar { - display: flex; + display: grid; + grid-template-columns: minmax(0, 1fr); + inline-size: fit-content; + max-inline-size: 100%; flex-wrap: wrap; align-items: center; justify-content: space-between; @@ -145,6 +148,11 @@ } @media (min-width: 48rem) { + .toolbar { + display: flex; + inline-size: auto; + } + .search { order: 0; inline-size: 20rem;