diff --git a/README.md b/README.md index 09eff0d..512cbac 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,8 @@ npm test --prefix backend npm test --prefix frontend ``` +The complete clean-install, MongoDB and Playwright commands are documented in [Automated local testing](docs/testing.md). Automated tests run locally; browser tests use the production frontend, real API and an isolated database. Automatic execution on pull requests is optional future work requiring runner access from the course staff who administer the repository. GitHub Actions is not required by the assignment. + `npm run test:integration --prefix backend` also runs the API against a temporary MongoDB database (`MONGODB_TEST_URI`). The tests never change the deployed catalog. What is tested is described in [docs/backend.md](docs/backend.md#tests) and [frontend/README.md](frontend/README.md#tests). Linting, formatting and the production builds are checked with: diff --git a/backend/package-lock.json b/backend/package-lock.json index 8c63946..5f86032 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1449,18 +1449,18 @@ } }, "node_modules/body-parser": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", - "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", - "content-type": "^2.0.0", + "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", - "iconv-lite": "^0.7.2", + "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", - "qs": "^6.15.2", + "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" }, @@ -2016,9 +2016,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", - "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "funding": [ { "type": "github", @@ -2879,9 +2879,9 @@ "license": "MIT" }, "node_modules/qs": { - "version": "6.16.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz", - "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==", + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "license": "BSD-3-Clause", "dependencies": { "es-define-property": "^1.0.1", diff --git a/backend/package.json b/backend/package.json index be5f607..36946af 100644 --- a/backend/package.json +++ b/backend/package.json @@ -20,7 +20,7 @@ "db:explain": "npm run build && node --env-file-if-exists=.env dist/cli.js explain", "db:verify": "npm run build && node --env-file-if-exists=.env dist/cli.js verify", "test": "npm run build && node --test tests/validation.test.js tests/graphql.test.js tests/lineups.test.js tests/ratings.test.js", - "test:integration": "npm run build && node --env-file-if-exists=.env --test tests/integration.test.js tests/graphql.integration.test.js tests/lineups.integration.test.js tests/ratings.integration.test.js" + "test:integration": "npm run build && node --env-file-if-exists=.env --test tests/integration.test.js tests/graphql.integration.test.js tests/lineups.integration.test.js tests/ratings.integration.test.js tests/user-data.integration.test.js" }, "dependencies": { "@apollo/server": "^5.5.1", diff --git a/backend/tests/e2e-server.js b/backend/tests/e2e-server.js new file mode 100644 index 0000000..5d4de77 --- /dev/null +++ b/backend/tests/e2e-server.js @@ -0,0 +1,54 @@ +// Dedicated Playwright API. Never loads .env or uses MONGODB_URI/MONGODB_DB. +import { randomUUID } from "node:crypto"; +import { MongoClient } from "mongodb"; +import { importDataset, loadDataset } from "../dist/database.js"; +import { createMongoCatalog } from "../dist/catalog.js"; +import { createMongoLineupStore } from "../dist/lineups.js"; +import { createMongoRatingStore } from "../dist/ratings.js"; +import { startServer } from "../dist/server.js"; + +const uri = process.env.MONGODB_TEST_URI || "mongodb://127.0.0.1:27028"; +// Tests are deliberately limited to a local, separately configured test service. +if (!/^mongodb:\/\/(127\.0\.0\.1|localhost):\d+(\/[^?]*)?(\?.*)?$/.test(uri)) { + throw new Error( + "E2E requires a loopback MONGODB_TEST_URI with an explicit port.", + ); +} +const name = `vm26_e2e_${randomUUID().replaceAll("-", "")}`; +const client = new MongoClient(uri, { serverSelectionTimeoutMS: 5000 }); +const db = client.db(name); +let server; +let stopping = false; +async function stop() { + if (stopping) return; + stopping = true; + try { + await server?.stop(); + // The database name is generated here, never supplied by environment/config. + await db.dropDatabase(); + } finally { + await client.close(); + } +} +try { + await client.connect(); + await importDataset(db, await loadDataset()); + server = await startServer({ + port: 3101, + catalog: createMongoCatalog(db), + lineups: createMongoLineupStore(db), + ratings: createMongoRatingStore(db), + }); + console.log(`E2E API ready: ${server.url}; isolated database ${name}`); + for (const signal of ["SIGINT", "SIGTERM"]) { + process.once(signal, () => { + stop().catch((error) => { + console.error(error); + process.exitCode = 1; + }); + }); + } +} catch (error) { + await stop(); + throw error; +} diff --git a/backend/tests/graphql.integration.test.js b/backend/tests/graphql.integration.test.js index 2a17c79..288d73c 100644 --- a/backend/tests/graphql.integration.test.js +++ b/backend/tests/graphql.integration.test.js @@ -633,6 +633,10 @@ test("real MongoDB: GraphQL queries, pagination, squads and indexes", async (t) ) ).body.singleResult; for (const [sort, expected] of Object.entries({ + GOALS_DESC: ["1", "2", "3", "7"], + ASSISTS_DESC: ["1", "2", "3", "7"], + MATCHES_DESC: ["1", "2", "3", "7"], + RATING_DESC: ["1", "2", "3", "7"], NAME_ASC: ["1", "2", "3", "7"], NAME_DESC: ["7", "2", "3", "1"], HEIGHT_DESC: ["1", "2", "3", "7"], diff --git a/backend/tests/user-data.integration.test.js b/backend/tests/user-data.integration.test.js new file mode 100644 index 0000000..97fda6d --- /dev/null +++ b/backend/tests/user-data.integration.test.js @@ -0,0 +1,235 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { MongoClient } from "mongodb"; +import { importDataset, loadDataset } from "../dist/database.js"; +import { createMongoCatalog } from "../dist/catalog.js"; +import { createMongoLineupStore } from "../dist/lineups.js"; +import { createMongoRatingStore } from "../dist/ratings.js"; +import { createApolloServer } from "../dist/server.js"; + +test("real MongoDB: saved-data GraphQL mutations, validation and tied pagination", async (t) => { + assert.ok( + process.env.MONGODB_TEST_URI, + "Set MONGODB_TEST_URI to run integration tests", + ); + const client = await new MongoClient(process.env.MONGODB_TEST_URI, { + serverSelectionTimeoutMS: 5000, + }).connect(); + const db = client.db(`vm26_test_${randomUUID().replaceAll("-", "")}`); + const server = createApolloServer(); + await server.start(); + try { + const dataset = await loadDataset(); + await importDataset(db, dataset); + const ratings = createMongoRatingStore(db); + const contextValue = { + catalog: createMongoCatalog(db), + lineups: createMongoLineupStore(db), + ratings, + }; + const execute = async (query, variables = {}) => { + const response = await server.executeOperation( + { query, variables }, + { contextValue }, + ); + assert.equal(response.body.kind, "single"); + return response.body.singleResult; + }; + const ownerId = randomUUID(); + const otherOwner = randomUUID(); + const input = { + ownerId, + playerId: "737066", + stars: 4, + comment: " Persist me ", + }; + const rate = `mutation($input: RatingInput!) { ratePlayer(input: $input) { playerId stars comment createdAt updatedAt player { id name } } }`; + const find = `query($ownerId: ID!) { myRating(ownerId: $ownerId, playerId: "737066") { stars comment } myRatings(ownerId: $ownerId, limit: 1) { totalCount items { playerId } hasNextPage } }`; + await t.test( + "rating mutations round-trip through MongoDB, isolate owners and preserve creation time", + async () => { + const first = await execute(rate, { input }); + assert.equal(first.errors, undefined); + assert.equal(first.data.ratePlayer.comment, "Persist me"); + assert.equal(first.data.ratePlayer.player.name, "Erling Haaland"); + const updated = await execute(rate, { + input: { ...input, stars: 2, comment: "Updated" }, + }); + assert.equal(updated.errors, undefined); + assert.equal( + updated.data.ratePlayer.createdAt, + first.data.ratePlayer.createdAt, + ); + assert.equal( + await db.collection("ratings").countDocuments({ ownerId }), + 1, + ); + const read = await execute(find, { ownerId }); + assert.equal(read.data.myRating.stars, 2); + assert.equal(read.data.myRating.comment, "Updated"); + assert.equal(read.data.myRatings.totalCount, 1); + const other = await execute(find, { ownerId: otherOwner }); + assert.equal(other.data.myRating, null); + assert.equal(other.data.myRatings.totalCount, 0); + }, + ); + await t.test( + "invalid rating mutations and pagination leave stored data untouched", + async () => { + for (const change of [ + { stars: 0 }, + { stars: 6 }, + { comment: "x".repeat(301) }, + { ownerId: "bad" }, + { playerId: "999999999" }, + ]) { + const result = await execute(rate, { + input: { ...input, ...change }, + }); + assert.equal(result.errors[0].extensions.code, "BAD_USER_INPUT"); + } + for (const args of [ + "limit: 0", + "limit: 51", + "offset: -1", + "offset: 10001", + ]) { + const result = await execute( + `{ myRatings(ownerId: "${ownerId}", ${args}) { totalCount } }`, + ); + assert.equal(result.errors[0].extensions.code, "BAD_USER_INPUT"); + } + assert.equal( + (await ratings.find(ownerId, "737066")).comment, + "Updated", + ); + assert.equal(await db.collection("ratings").countDocuments(), 1); + }, + ); + await t.test( + "all rating sort orders page deterministically across tied names, stars and timestamps", + async () => { + const ids = ["737066", "534670", "73409"]; + const tiedOwner = randomUUID(); + // Insert in reverse order so MongoDB natural insertion order cannot satisfy the expected order. + for (const playerId of ids.slice().reverse()) { + await ratings.save( + { ownerId: tiedOwner, playerId, stars: 4, comment: "Tie" }, + "2026-10-01T00:00:00.000Z", + ); + } + await db + .collection("players") + .updateMany({ id: { $in: ids } }, { $set: { name: "Same name" } }); + const query = `query($ownerId: ID!, $sort: RatingSort!, $offset: Int!) { myRatings(ownerId: $ownerId, sort: $sort, limit: 1, offset: $offset) { items { playerId } totalCount hasNextPage } }`; + for (const sort of ["NAME_ASC", "STARS_DESC", "UPDATED_DESC"]) { + const walk = async () => { + const seen = []; + for (let offset = 0; offset < 4; offset++) { + const result = await execute(query, { + ownerId: tiedOwner, + sort, + offset, + }); + assert.equal(result.errors, undefined); + assert.equal(result.data.myRatings.totalCount, 3); + assert.equal(result.data.myRatings.hasNextPage, offset < 2); + seen.push( + ...result.data.myRatings.items.map((item) => item.playerId), + ); + } + return seen; + }; + assert.deepEqual(await walk(), ids.slice().sort(), sort); + assert.deepEqual( + await walk(), + ids.slice().sort(), + `${sort} repeated`, + ); + } + await importDataset(db, dataset); + }, + ); + await t.test( + "lineup mutation replaces slots, validates input and reads back via GraphQL", + async () => { + const save = `mutation($input: LineupInput!) { saveLineup(input: $input) { id name formation slots { slot playerId player { name } } } }`; + const lineup = { + ownerId, + name: " API XI ", + formation: "4-3-3", + slots: [{ slot: "FWD-2", playerId: "737066" }], + }; + const result = await execute(save, { input: lineup }); + assert.equal(result.errors, undefined); + assert.equal(result.data.saveLineup.name, "API XI"); + const query = `query($ownerId: ID!) { myLineup(ownerId: $ownerId) { name slots { playerId player { name } } } }`; + assert.equal( + (await execute(query, { ownerId })).data.myLineup.slots[0].player + .name, + "Erling Haaland", + ); + assert.equal( + (await execute(query, { ownerId: otherOwner })).data.myLineup, + null, + ); + for (const change of [ + { name: " " }, + { formation: "2-2-6" }, + { slots: [...lineup.slots, ...lineup.slots] }, + { slots: [{ slot: "FWD-2", playerId: "999999999" }] }, + ]) { + const invalid = await execute(save, { + input: { ...lineup, ...change }, + }); + assert.equal(invalid.errors[0].extensions.code, "BAD_USER_INPUT"); + } + assert.equal( + (await execute(query, { ownerId })).data.myLineup.slots.length, + 1, + ); + const cleared = await execute(save, { + input: { ...lineup, slots: [] }, + }); + assert.equal(cleared.errors, undefined); + assert.deepEqual(cleared.data.saveLineup.slots, []); + assert.equal(await db.collection("lineups").countDocuments(), 1); + const remove = `mutation($ownerId: ID!) { deleteLineup(ownerId: $ownerId) }`; + assert.equal( + (await execute(remove, { ownerId })).data.deleteLineup, + true, + ); + assert.equal( + (await execute(remove, { ownerId })).data.deleteLineup, + false, + ); + assert.equal((await execute(query, { ownerId })).data.myLineup, null); + }, + ); + await t.test( + "delete mutation is idempotent and the next query is empty", + async () => { + const remove = `mutation($ownerId: ID!) { removeRating(ownerId: $ownerId, playerId: "737066") }`; + assert.equal( + (await execute(remove, { ownerId })).data.removeRating, + true, + ); + assert.equal( + (await execute(remove, { ownerId })).data.removeRating, + false, + ); + const read = await execute(find, { ownerId }); + assert.equal(read.data.myRating, null); + assert.equal(read.data.myRatings.totalCount, 0); + }, + ); + } finally { + await server.stop(); + try { + await db.dropDatabase(); + } finally { + await client.close(); + } + } +}); diff --git a/database/compose.test.yaml b/database/compose.test.yaml new file mode 100644 index 0000000..c514c6f --- /dev/null +++ b/database/compose.test.yaml @@ -0,0 +1,20 @@ +# Disposable test service, separate from compose.yaml and its persistent volume. +services: + mongodb-test: + image: mongo:8.0 + ports: + - "127.0.0.1:27028:27017" + tmpfs: + - /data/db + healthcheck: + test: + [ + "CMD", + "mongosh", + "--quiet", + "--eval", + "db.adminCommand({ ping: 1 }).ok", + ] + interval: 2s + timeout: 5s + retries: 30 diff --git a/docs/asset-measurements.json b/docs/asset-measurements.json index 9ad882f..92b62c1 100644 --- a/docs/asset-measurements.json +++ b/docs/asset-measurements.json @@ -4,7 +4,7 @@ { "file": "index.html", "bytes": 496, - "gzipBytes": 318 + "gzipBytes": 316 }, { "file": "assets/ar-Be8Ju1cG.svg", @@ -132,14 +132,14 @@ "gzipBytes": 4789 }, { - "file": "assets/index-CRC6q2Di.css", - "bytes": 49633, - "gzipBytes": 8925 + "file": "assets/index-DqN-Ocbu.css", + "bytes": 49420, + "gzipBytes": 8913 }, { - "file": "assets/index-DCHIba9g.js", - "bytes": 596714, - "gzipBytes": 177593 + "file": "assets/index-DvNJfnGc.js", + "bytes": 597347, + "gzipBytes": 177795 }, { "file": "assets/iq-Dp8HDzo2.svg", diff --git a/docs/sustainability.md b/docs/sustainability.md index c14109e..5d9b47d 100644 --- a/docs/sustainability.md +++ b/docs/sustainability.md @@ -6,7 +6,7 @@ Reviewed 29 October 2026 against the prepared dataset: 48 teams and 1,243 player | View | Loading boundary | Selected data and trade-off | | ------------------ | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Teams catalog | 12 teams per explicit page | Card fields only; no squads or detail statistics. Search, group and sort run before pagination on the server. No next-page prefetch. | +| Teams catalog | 12 teams per explicit page | Identity, FIFA ranking and coach only; no squads or group-stage totals. Search, group and sort run before pagination on the server. No next-page prefetch. | | Players catalog | 12 players per explicit page | Identity, country, position, club and birth date used by cards. Detailed statistics load only on a player page. | | Player team filter | One request, at most 50 team IDs/names | This intentionally loads all 48 **filter options**, not the player collection or full team records. It is reused for the session. If the tournament expands past 50 teams, this selector needs pagination. | | My Ratings | 10 ratings per page | Rating text, timestamps and the small player summary used by the list/editor. No player statistics or squad. | @@ -16,7 +16,7 @@ Reviewed 29 October 2026 against the prepared dataset: 48 teams and 1,243 player | Standings | At most 50 teams per API request | The all-groups view intentionally displays all 48 teams. It follows `hasNextPage`, checks for progress, and requests global groups/third-place results only while absent from cache. | | Knockout | One fixed tournament bracket | The complete bracket is needed for the overview; this is not an unbounded user-generated collection. | -The API validates limits of 1–50, offsets of 0–10,000 and search length up to 100 before accessing the catalog. Existing backend tests check invalid limits, combined filters and pagination. Catalog navigation never walks through all pages automatically. Search currently requests on each input change; obsolete requests can be unsubscribed, but this is not a debounce and a fast typist can still initiate several requests. Debouncing remains a possible latency/traffic trade-off. +The API validates limits of 1–50, offsets of 0–10,000 and search length up to 100 before accessing the catalog. Existing backend tests check invalid limits, combined filters and pagination. Catalog navigation never walks through all pages automatically. Catalog search is submitted with the Search button or Enter; typing alone sends no query. Filter and sort changes request the selected view, while obsolete requests can be unsubscribed. Rapid catalog control changes now commit URL state synchronously so a later change does not discard an earlier submitted search. ## Cache reuse, cancellation and saved data @@ -55,8 +55,8 @@ npm run lint --prefix frontend | Sequential flow | New API requests | Request body bytes | Response body bytes | | ----------------------------------------------- | ---------------: | -----------------: | ------------------: | -| Teams page 1, cold | 1 | 668 | 1,329 | -| Teams page 2 | 1 | 670 | 1,236 | +| Teams page 1, cold | 1 | 655 | 1,386 | +| Teams page 2 | 1 | 657 | 1,271 | | Teams back to page 1 | 0 | 0 | 0 | | Players page 1 + team options | 2 | 915 | 4,887 | | Players page 2 | 1 | 659 | 2,329 | @@ -72,7 +72,7 @@ npm run lint --prefix frontend The forced two-page case verifies that the second response contains only `teams`, with neither global field. The filtered standings response also contains only `teams`. These assertions protect the optimization if pagination or metadata loading changes. -[asset-measurements.json](asset-measurements.json) lists all production files and offline gzip sizes. Before externalizing flags, JavaScript was 626.77 kB (187.69 kB gzip); after, it is 596.71 kB (179.54 kB gzip), using the same local installed toolchain. This saves about 8.15 kB in the compressed initial JS, while visible flags have their own transfers. The CSS is 49.63 kB (8.91 kB gzip). A complete asset inventory is not the amount transferred by one visit. The remaining JS exceeds Vite's 500 kB warning threshold; route splitting is a possible future improvement with extra chunk-loading requests. No bundle-warning suppression was added. The before/after figures here are from Vite’s build summary; the independent gzip estimates in the JSON inventory can differ with compressor settings. +[asset-measurements.json](asset-measurements.json) lists the current production files and offline gzip sizes. In the earlier flag-externalization comparison, JavaScript was 626.77 kB (187.69 kB gzip); after, it is 596.71 kB (179.54 kB gzip), using the same local installed toolchain. This saves about 8.15 kB in the compressed initial JS, while visible flags have their own transfers. That comparison used CSS of 49.63 kB (8.91 kB gzip); subsequent UI changes are reflected in the current JSON inventory. A complete asset inventory is not the amount transferred by one visit. The remaining JS exceeds Vite's 500 kB warning threshold; route splitting is a possible future improvement with extra chunk-loading requests. No bundle-warning suppression was added. The before/after figures here are from Vite’s build summary; the independent gzip estimates in the JSON inventory can differ with compressor settings. ## Production configuration and remaining deployment verification diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..59cdf6e --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,138 @@ +# Automated local testing + +Automated tests run locally. The repository is administered by the course staff, runner access is currently unavailable, and the assignment does not require GitHub Actions. + +The test layers have different jobs. Vitest and Testing Library check UI behavior with a mocked GraphQL transport. Node's unit/API tests run the real schema with controlled stores. MongoDB integration tests run real aggregations, validation, indexes and mutations. Playwright exercises the production frontend build through its HTTP proxy, the GraphQL backend and a separately seeded real MongoDB database. + +## Clean setup + +Use Node 24 LTS and npm. The frontend declares Node >=22.22.0, matching React Router's actual engine requirement; the backend declares >=22.12. Dependencies and Playwright's browser revision are recorded in the committed lockfiles. The recorded local verification used Node 24 on macOS. + +From the repository root: + +```sh +npm ci --prefix backend --include=optional +npm ci --prefix frontend --include=optional +npm run build --prefix backend +npm run build --prefix frontend +npm run typecheck:e2e --prefix frontend +npm run lint --prefix backend +npm run lint --prefix frontend +npm run format:check --prefix backend +npm run format:check --prefix frontend +npm test --prefix backend +npm test --prefix frontend +``` + +Use `npm ci` instead of reusing a platform's `node_modules` directory. Vite/Rolldown and related tools have platform-specific optional binaries: keep optional dependencies enabled and retain all platform entries in the lockfile. Do not use `--omit=optional`, copy `node_modules` between macOS and Linux, or remove platform entries to fix an installation. Verify each target platform with its own clean installation; the recorded results do not establish Linux compatibility. npm 11 can report install-script notices for optional macOS `fsevents` and backend dependencies; no blanket script approval was needed for the verified build/test commands. The clean backend install also exposed audit advisories in transitive `body-parser`, `fast-uri` and `qs`; compatible lockfile updates resolved the reported advisories without a major-version upgrade. Both clean installs subsequently reported zero audit vulnerabilities at verification time. + +Vitest explicitly includes only `src/**/*.test.{ts,tsx}`. Playwright owns `e2e/*.spec.ts`; the two runners must not discover each other's tests. E2E TypeScript has a separate `tsconfig.e2e.json`, checked locally with `npm run typecheck:e2e --prefix frontend`, and the component render helper uses the same DOM RouterProvider as production. + +## Start a disposable MongoDB service + +Do **not** use a shared/production MongoDB URI or the development data volume for these commands. This Compose file exposes a separate local port and stores its data in temporary container memory: + +```sh +docker compose -f database/compose.test.yaml up -d --wait +``` + +Alternatively, with MongoDB 8.0 installed locally, keep this process running in its own terminal: + +```sh +test_db_dir=$(mktemp -d) +mongod --bind_ip 127.0.0.1 --port 27028 --dbpath "$test_db_dir" +``` + +Stop that process with Ctrl+C after testing. Port 27028 must be free. A fresh temporary directory separates it from any development MongoDB installation. The local verification used this native alternative. The Compose path provides a disposable local container setup, but was not exercised in the recorded native MongoDB run. + +Run the complete MongoDB suites: + +```sh +MONGODB_TEST_URI=mongodb://127.0.0.1:27028 npm run test:integration --prefix backend +``` + +Each integration suite generates a unique `vm26_test_` database name, imports its own fixtures and drops only that database in `finally`. A database name supplied in a connection string is not used as the test database name. Integration tests require `MONGODB_TEST_URI`; pass it explicitly as above. The existing integration command can load `backend/.env` when run from that directory, so explicitly override the test URI and never point it at a shared service. Production `MONGODB_DB` is never used by the test suites. + +The integration tests check filtering and sorting before pagination, real query plans, catalog validation, World Cup statistics and knockout/third-place queries. The added saved-data API suite exercises rating create/update/delete and lineup save/replace/delete through the GraphQL schema with MongoDB stores. It checks owner separation, idempotent deletion, creation-time preservation and invalid inputs without changing the saved documents. Rating pagination deliberately ties **names, stars and update timestamps**, inserts in reverse order, walks each sort order twice and asserts the exact ID order and page flags. Catalog fixtures also exercise tied values for goals, assists, appearances and rating, in addition to existing name/height/value/date sorts. + +## Browser tests + +Install the pinned Chromium revision once: + +```sh +npm run test:e2e:install --prefix frontend +``` + +On Linux, install OS dependencies as well (this may require sudo): + +```sh +cd frontend +npx playwright install --with-deps chromium +cd .. +``` + +With the disposable MongoDB process running: + +```sh +MONGODB_TEST_URI=mongodb://127.0.0.1:27028 npm run test:e2e --prefix frontend +``` + +No frontend/backend processes need to be started manually. Playwright starts: + +- The API on **3101**, using the production server, schema and MongoDB stores. `backend/tests/e2e-server.js` imports the prepared dataset into a generated `vm26_e2e_` database. It does not load `.env`, read `MONGODB_URI`/`MONGODB_DB`, or accept a database name from configuration. Its test URI must be a loopback MongoDB URL with an explicit port; otherwise it refuses to start. Without `MONGODB_TEST_URI`, it uses `mongodb://127.0.0.1:27028`. +- Vite's production preview on **4173**, after building the app. The build forces `VITE_GRAPHQL_URL=/project2/graphql`, and the preview forces `BACKEND_URL=http://127.0.0.1:3101`. Ambient development backend settings cannot redirect the browser to production. + +Both have `reuseExistingServer: false` and fixed ports: if another process occupies a test port, the run fails rather than silently using it. The API handles SIGTERM/SIGINT, stops HTTP, drops its generated database and closes the client. Playwright gives it ten seconds for graceful shutdown. An uncatchable termination such as SIGKILL can leave a test database behind; the dedicated disposable MongoDB service limits this to test data. Each subsequent run uses a new name. + +Browser scenarios cover: + +1. Submit search, filter to Norway, sort by goals, verify the exact first and second result pages against prepared source data, open a profile, reload it, return with all URL filters/page intact, and navigate back to the first page. The fixture has multiple equal goal values; MongoDB's binary name/ID tie-break determines expected order. +2. Create a rating through the form, reload to retrieve it with a new Apollo cache, update it, reload My Ratings and verify the update, confirm another browser context has an empty list, then delete and reload to verify removal. A comment without stars cannot be saved. The star selection uses the keyboard against the actual radio input. +3. Select a player in My XI, save a lineup, reload to retrieve its name and player, remove the player, save and reload again to verify slot replacement. +4. Recover from empty results, handle a malformed player URL, verify a real API validation error for an oversized page, and recover after one deliberately aborted HTTP request. + +Persistence and catalog scenarios do **not** mock GraphQL or MongoDB. Only the recovery scenario aborts one request and then retries against the real API. External FotMob requests are blocked in the primary test page to make the run independent of image-host availability and exercise the existing local image fallback. Each test gets a fresh browser context/anonymous owner; one worker avoids shared-service scheduling noise. Assertions wait on visible state and expected results rather than fixed sleeps. + +A detail-navigation scenario also checks team → player → team return chains after reload and returning to the original filtered Standings, Knockout and My Ratings views. + +Additional browser checks verify that menu links open fresh catalogs, explicit detail-return links and browser Back retain results, refreshed detail pages retain their return URL, content focus has no outline, interactive keyboard focus remains visible, and all six main sections fit a 320 px viewport. + +The new browser sequence exposed a real race: consecutive catalog control changes could build on an older URL and discard the submitted search. Teams and Players now flush their user-initiated filter URL updates before the next control event. Component regression tests reproduce consecutive submit/filter/sort events in the same update and verifies every parameter survives. Additional component tests verify that invalid rating/lineup drafts do not send mutations and can subsequently be saved without losing the draft. + +Playwright keeps traces and screenshots on failure, with an HTML report in `frontend/playwright-report/` and attachments in `frontend/test-results/`. These generated directories are ignored by Git. Inspect a local report with: + +```sh +cd frontend +npx playwright show-report +``` + +After testing with Compose: + +```sh +docker compose -f database/compose.test.yaml down +``` + +The Playwright server lifecycle follows the [official web-server configuration](https://playwright.dev/docs/test-webserver), with isolated ports and graceful shutdown rather than reusing a developer's running app. + +## Optional future pull request automation + +Automatic execution on pull requests is optional future work, not an active or required repository check. It requires available runners and agreement with the course staff who administer the repository. Until that access is provided, contributors should run the local commands above before requesting review; no required GitHub Actions checks or branch-protection changes are assumed. + +If automation is introduced later, it should run the same local scripts against a disposable MongoDB service, preserve the existing database isolation and cleanup, install Playwright's pinned Chromium and platform dependencies, and retain failure diagnostics. Environment-sensitive Playwright settings remain available for that future use; they do not schedule or execute tests on pull requests. + +## Verification record + +Local verification results are recorded after a clean install below. The local machine is macOS arm64 with Node 24.21.0, npm 11.19.0 and MongoDB 8.0.34. Linux, container-based execution and hosted runner results have not been verified; they are not implied by a local macOS run. Browser coverage currently uses Chromium desktop, not Firefox/WebKit or a mobile-browser matrix. Vite's existing large-JavaScript-chunk warning remains informational and unrelated to test success. + +| Check after clean installation | Result | +| -------------------------------- | ------------------------------------------------------------------------------- | +| Frontend Vitest | 131 passed | +| Backend unit/API | 110 passed | +| MongoDB integration | 27 passed | +| Playwright Chromium | 7 scenarios passed (the original four also passed 12/12 with `--repeat-each=3`) | +| Both builds, ESLint and Prettier | Passed | +| Browser-test TypeScript check | Passed | + +The dedicated test service was checked after the suites: no `vm26_test_*` or `vm26_e2e_*` databases remained. These are local results only; no hosted runner execution was verified. + +On 30 October 2026, workflow removal was verified by rerunning both builds, ESLint, Prettier, browser-test TypeScript checking, all 131 frontend tests, 110 backend unit/API tests, 27 MongoDB integration tests and 7 Playwright scenarios locally. All passed, and test database cleanup was verified. This rerun reused installed dependencies; it did not repeat the earlier clean installation or establish results on Linux or hosted runners. The existing Vite large-chunk warning remained. diff --git a/docs/transfer-measurements.json b/docs/transfer-measurements.json index 5f1f53d..af5cc01 100644 --- a/docs/transfer-measurements.json +++ b/docs/transfer-measurements.json @@ -8,16 +8,16 @@ { "flow": "Teams page 1 (cold)", "requests": 1, - "requestBytes": 668, - "responseBytes": 1329, - "gzipResponseBytes": 386 + "requestBytes": 655, + "responseBytes": 1386, + "gzipResponseBytes": 504 }, { "flow": "Teams page 2", "requests": 1, - "requestBytes": 670, - "responseBytes": 1236, - "gzipResponseBytes": 341 + "requestBytes": 657, + "responseBytes": 1271, + "gzipResponseBytes": 443 }, { "flow": "Teams back to page 1", @@ -107,9 +107,9 @@ "requests": [ { "operation": "Teams", - "requestBytes": 668, - "responseBytes": 1329, - "gzipResponseBytes": 386, + "requestBytes": 655, + "responseBytes": 1386, + "gzipResponseBytes": 504, "fields": [ "teamGroups", "teams" @@ -117,9 +117,9 @@ }, { "operation": "Teams", - "requestBytes": 670, - "responseBytes": 1236, - "gzipResponseBytes": 341, + "requestBytes": 657, + "responseBytes": 1271, + "gzipResponseBytes": 443, "fields": [ "teams" ] diff --git a/frontend/.gitignore b/frontend/.gitignore index 6fe064a..9969cbf 100644 --- a/frontend/.gitignore +++ b/frontend/.gitignore @@ -27,3 +27,7 @@ dist-ssr *.njsproj *.sln *.sw? + +# Playwright artifacts +playwright-report/ +test-results/ diff --git a/frontend/README.md b/frontend/README.md index c3c4ba8..73149f7 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -94,12 +94,12 @@ These addresses also work when opened directly or reloaded: the Vite dev server - **Squad page.** **View squad** on a team card is a link to `/teams/:teamId`. The page loads the team and its players with the `team` GraphQL query (`TEAM_QUERY` in `src/api/teams.ts`, `useTeam` in `src/hooks/useTeam.ts`). Players are grouped into goalkeepers, defenders, midfielders and forwards (`src/data/players.ts`). - **Player portraits.** Each squad row shows a small portrait from FotMob's image server, `https://images.fotmob.com/image_resources/playerimages/{id}.png`, since the imported player IDs are FotMob IDs. Images load lazily; missing or failing images are replaced with the local `player-placeholder.svg`. The portraits have empty alternative text, because the row header next to them already names the player. - **Loading, errors and unknown teams.** The squad page shows a message while loading and a **Try again** button if the request fails. A malformed ID in the address (for example `/teams/abc`) is never sent to the server, and both malformed and unknown IDs show "Team not found" with a link back to Teams. -- **Returning to Teams.** The squad page's **All teams** link, the Teams link in the header and the logo all lead back to the Teams page with the search, group, sort and page the user last used there. Browser Back does the same, because the filters are part of the address. +- **Returning to Teams.** The squad page's **All teams** link restores the search, group, sort and page encoded in the detail URL, including after reload. Browser Back also restores the previous address. The Teams menu link and logo always open the default first page; Players follows the same menu-reset rule. - **Back and Forward.** Every page has its own address, so Back and Forward move between pages as expected. Teams filter changes replace the current history entry; Players filter and page changes add entries so their previous states are reachable with Back/Forward. The scroll position is restored on Back and Forward (`ScrollRestoration`); new pages start at the top. - **Fewer requests.** Apollo Client keeps successful results in its cache for the rest of the visit, as described in [State management](#state-management). Going back to a page or to a filter combination that was already shown does not send a new request and shows the page immediately. - **Active navigation.** The Teams link is highlighted on the Teams page and on squad pages. It has `aria-current="page"` on the Teams page and `aria-current="true"` on squad pages, where Teams is the current section but not the current page. - **Unavailable sections.** Knockout and My Ratings are planned but not built yet. They are shown muted with a "Soon" label, are not links and cannot be focused, and screen readers hear "coming soon". -- **Page titles and focus.** Each page sets the browser tab title, for example "Norway squad – VM26" (`usePageTitle`). After moving to another page, focus moves to the new page's main heading, as after a full page load, so keyboard and screen reader users start at the new content. Filter changes keep focus where it is. A "Skip to main content" link is the first thing Tab reaches when the app loads. +- **Page titles and focus.** Each page sets the browser tab title, for example "Norway squad – WC26" (`usePageTitle`). After moving to another page, focus moves to the new page's main heading, as after a full page load, so keyboard and screen reader users start at the new content. Filter changes keep focus where it is. A "Skip to main content" link is the first thing Tab reaches when the app loads. ## Standings page @@ -154,3 +154,7 @@ Players component coverage is in `pages/PlayersPage/PlayersPage.test.tsx`: bound For checks against local MongoDB and the real backend, see [Players live verification](../docs/players-verification.md). These are separate from the mocked component suite. The page tests also run the axe accessibility checks with `expectNoAxeViolations` (`src/test/axe.ts`); see [docs/accessibility.md](../docs/accessibility.md). Interactions are simulated with `@testing-library/user-event`, the way a user types and clicks. The snapshot is stored in `components/TeamCard/__snapshots__/`; after an intended change to the card, it is updated with `npx vitest run -u`. + +Full browser tests use Playwright against the production build, real backend and isolated MongoDB. See [Automated local testing](../docs/testing.md) for setup, commands, isolation and failure reports. + +Detail links carry their originating route, filters and parent route in browser history state. Team/player return links therefore lead back to the actual source (squad, player, catalog, Standings, Knockout or My Ratings), including after refresh. When the source is still the immediately previous history entry, return uses browser Back to restore its scroll position. Otherwise it follows the explicit internal return URL. A directly opened detail URL without source state falls back to its catalog. Menu links always start fresh. diff --git a/frontend/e2e/application.spec.ts b/frontend/e2e/application.spec.ts new file mode 100644 index 0000000..bee9676 --- /dev/null +++ b/frontend/e2e/application.spec.ts @@ -0,0 +1,266 @@ +import { readFileSync } from 'node:fs' +import { expect, test } from '@playwright/test' + +type Player = { id: string; name: string; teamId: string; goals: number | null } +const players: Player[] = JSON.parse( + readFileSync(new URL('../../database/prepared/players.json', import.meta.url), 'utf8'), +) +const matching = players + .filter((p) => p.teamId === '8492' && p.name.toLowerCase().includes('a')) + .sort( + (a, b) => + (b.goals ?? -Infinity) - (a.goals ?? -Infinity) || + (a.name < b.name ? -1 : a.name > b.name ? 1 : a.id < b.id ? -1 : 1), + ) + +test.beforeEach(async ({ page }) => { + // External photos are not part of the application under test. Exercise its local fallback. + await page.route('https://images.fotmob.com/**', (route) => route.abort()) +}) + +test('search, filter, sort, paginate, reload details and return to the same results', async ({ + page, +}) => { + await page.goto('/project2/players') + await expect(page.locator('.player-card')).toHaveCount(12) + await page.getByLabel('Search players', { exact: true }).fill('a') + await page.getByRole('button', { name: 'Search', exact: true }).click() + await page.getByLabel('National team').selectOption('8492') + await page.getByLabel('Sort by').selectOption('GOALS_DESC') + await expect(page.locator('.player-card h2')).toHaveText(matching.slice(0, 12).map((p) => p.name)) + await page.getByRole('button', { name: 'Next page' }).click() + await expect(page.locator('.player-card h2')).toHaveText( + matching.slice(12, 24).map((p) => p.name), + ) + const resultsURL = page.url() + const selected = matching[12] + await page.locator('.player-card').first().click() + await expect(page.getByRole('heading', { level: 1, name: selected.name })).toBeVisible() + await page.reload() + await expect(page.getByRole('heading', { level: 1, name: selected.name })).toBeVisible() + await page.getByRole('link', { name: 'All players', exact: true }).click() + await expect(page).toHaveURL(resultsURL) + await expect(page.getByLabel('Search players', { exact: true })).toHaveValue('a') + await expect(page.getByLabel('National team')).toHaveValue('8492') + await expect(page.getByLabel('Sort by')).toHaveValue('GOALS_DESC') + await expect(page.locator('.player-card h2')).toHaveText( + matching.slice(12, 24).map((p) => p.name), + ) + await page.getByRole('button', { name: 'Previous page' }).click() + await expect(page.locator('.player-card h2')).toHaveText(matching.slice(0, 12).map((p) => p.name)) +}) + +test('ratings persist through reload, update and deletion; another browser has no saved ratings', async ({ + page, + browser, +}) => { + await page.goto('/project2/players/737066') + const comment = page.getByLabel('Comment (optional)') + await comment.fill('Browser persistence test') + await expect(page.getByRole('button', { name: 'Save rating', exact: true })).toHaveAttribute( + 'aria-disabled', + 'true', + ) + await page.getByRole('radio', { name: '4 stars', exact: true }).focus() + await page.keyboard.press('Space') + await page.getByRole('button', { name: 'Save rating', exact: true }).click() + await expect(page.getByText('Rating saved.', { exact: true })).toBeVisible() + await page.reload() + await expect(comment).toHaveValue('Browser persistence test') + await expect(page.getByRole('radio', { name: '4 stars', exact: true })).toBeChecked() + await comment.fill('Updated in the browser') + await page.getByRole('button', { name: 'Update rating', exact: true }).click() + await expect(page.getByText('Rating updated.', { exact: true })).toBeVisible() + await page.getByRole('link', { name: 'My Ratings', exact: true }).click() + await page.reload() + await expect(page.getByRole('list', { name: 'Your ratings' })).toContainText( + 'Updated in the browser', + ) + const other = await browser.newContext() + try { + const otherPage = await other.newPage() + await otherPage.goto('http://127.0.0.1:4173/project2/my-ratings') + await expect(otherPage.getByText('You have not rated any players yet.')).toBeVisible() + } finally { + await other.close() + } + await page.getByRole('link', { name: /Erling Haaland/ }).click() + await page.getByRole('button', { name: 'Remove rating', exact: true }).click() + await expect(page.getByText('Rating removed.', { exact: true })).toBeVisible() + await page.reload() + await expect(comment).toHaveValue('') + await page.getByRole('link', { name: 'My Ratings', exact: true }).click() + await expect(page.getByText('You have not rated any players yet.')).toBeVisible() +}) + +test('a lineup and its selected player survive a real reload', async ({ page }) => { + await page.goto('/project2/my-xi') + await page.getByRole('button', { name: 'Choose player for Forward 2', exact: true }).click() + await page.getByLabel('Search players for Forward 2').fill('Haaland') + await page.getByRole('button', { name: 'Search', exact: true }).click() + await page + .getByRole('button', { name: 'Select Erling Haaland for Forward 2', exact: true }) + .click() + await page.getByLabel('Lineup name').fill('Browser XI') + await page.getByRole('button', { name: 'Save lineup', exact: true }).click() + await expect(page.getByText(/^Saved /)).toBeVisible() + await page.reload() + await expect(page.getByLabel('Lineup name')).toHaveValue('Browser XI') + await expect( + page.getByRole('button', { name: 'Replace Erling Haaland as Forward 2', exact: true }), + ).toBeVisible() + await page + .getByRole('button', { name: 'Remove Erling Haaland from Forward 2', exact: true }) + .click() + await page.getByRole('button', { name: 'Save lineup', exact: true }).click() + await expect(page.getByText(/^Saved /)).toBeVisible() + await page.reload() + await expect( + page.getByRole('button', { name: 'Choose player for Forward 2', exact: true }), + ).toBeVisible() +}) + +test('empty results, invalid input and retry recover against the real API', async ({ + page, + request, +}) => { + await page.goto('/project2/players?search=no-such-player-xyz') + await expect(page.getByText(/No players on this page/)).toBeVisible() + await page.getByRole('button', { name: 'Reset filters' }).click() + await expect(page.locator('.player-card')).toHaveCount(12) + await page.goto('/project2/players/not-a-player-id') + await expect(page.getByRole('heading', { name: 'Player not found' })).toBeVisible() + const invalid = await request.post('/project2/graphql', { + data: { query: '{ players(limit: 51) { totalCount } }' }, + }) + expect((await invalid.json()).errors[0].extensions.code).toBe('BAD_USER_INPUT') + // Fail exactly one catalog request, then let retry reach the real backend and MongoDB. + await page.route('**/project2/graphql', async (route) => { + if (route.request().postDataJSON()?.operationName === 'Players') { + await page.unroute('**/project2/graphql') + await route.abort('failed') + } else { + await route.continue() + } + }) + await page.goto('/project2/players') + await expect(page.getByRole('alert')).toContainText('Could not load players') + await page.getByRole('button', { name: 'Try again', exact: true }).click() + await expect(page.locator('.player-card')).toHaveCount(12) +}) + +test('menu links start fresh, detail return survives refresh, and focus stays visually unobtrusive', async ({ + page, +}, testInfo) => { + await page.goto('/project2/teams?page=2') + await expect(page.locator('.team-card')).toHaveCount(12) + const firstTeam = await page.locator('.team-card h2').first().textContent() + await page + .getByRole('link', { name: /^View squad for/ }) + .first() + .click() + await expect(page.getByRole('heading', { level: 1, name: firstTeam! })).toBeVisible() + await page.reload() + await page.getByRole('link', { name: 'All teams', exact: true }).click() + await expect(page).toHaveURL(/\/teams\?page=2$/) + await expect(page.locator('.team-card h2').first()).toHaveText(firstTeam!) + await page.reload() + await page.getByRole('link', { name: 'My XI', exact: true }).click() + const heading = page.getByRole('heading', { level: 1, name: 'My XI' }) + await expect(heading).toBeFocused() + await expect(heading).toHaveCSS('outline-style', 'none') + await page.getByRole('link', { name: 'Teams', exact: true }).click() + await expect(page).toHaveURL(/\/project2\/teams$/) + await expect(page.locator('.team-card')).toHaveCount(12) + await expect(page.locator('.team-card').first()).toContainText('FIFA ranking') + await expect(page.locator('.team-card').first()).toContainText('Head coach') + await expect(page.locator('.team-card').first()).not.toContainText('Matches') + await expect(page.getByRole('heading', { level: 1, name: 'Teams' })).toHaveCSS( + 'outline-style', + 'none', + ) + await page.getByRole('link', { name: 'WC26, go to Teams' }).focus() + await page.keyboard.press('Tab') + await expect(page.getByRole('link', { name: 'Teams', exact: true })).toBeFocused() + await expect(page.getByRole('link', { name: 'Teams', exact: true })).toHaveCSS( + 'outline-style', + 'solid', + ) + await page.keyboard.press('Escape') + await page.screenshot({ path: testInfo.outputPath('teams-desktop.png'), fullPage: true }) + // All top-level catalogs follow the same reset rule. + await page.goto('/project2/players?page=2&sort=NAME_DESC') + await expect(page.locator('.player-card')).toHaveCount(12) + await page.getByRole('link', { name: 'My Ratings', exact: true }).click() + await page.getByRole('link', { name: 'Players', exact: true }).click() + await expect(page).toHaveURL(/\/project2\/players$/) + await page.getByRole('link', { name: 'Standings', exact: true }).click() + await expect(page.getByText('Data limitations.', { exact: true })).toHaveCount(0) + await page.setViewportSize({ width: 390, height: 844 }) + await page.getByRole('link', { name: 'Teams', exact: true }).click() + await expect(page.locator('.team-card')).toHaveCount(12) + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe( + true, + ) + await page.screenshot({ path: testInfo.outputPath('teams-mobile.png'), fullPage: true }) +}) + +test('all main sections fit narrow mobile screens', async ({ page }) => { + await page.setViewportSize({ width: 320, height: 760 }) + for (const section of ['teams', 'players', 'standings', 'knockout', 'my-xi', 'my-ratings']) { + await page.goto(`/project2/${section}`) + if (section === 'teams') await expect(page.locator('.team-card')).toHaveCount(12) + if (section === 'players') await expect(page.locator('.player-card')).toHaveCount(12) + if (section === 'standings') + await expect(page.getByRole('table', { name: 'Group A', exact: true })).toBeVisible() + if (section === 'knockout') await expect(page.locator('.knockout-match').first()).toBeVisible() + if (section === 'my-xi') + await expect( + page.getByRole('button', { name: 'Choose player for Forward 2', exact: true }), + ).toBeVisible() + if (section === 'my-ratings') + await expect(page.getByText('You have not rated any players yet.')).toBeVisible() + expect( + await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth), + section, + ).toBe(true) + } +}) + +test('detail back links restore the actual source and its parent after refresh', async ({ + page, +}) => { + await page.goto('/project2/teams?search=nor') + await page.getByRole('link', { name: 'View squad for Norway', exact: true }).click() + await page.getByRole('link', { name: 'Erling Haaland', exact: true }).click() + await page.reload() + await expect(page.getByRole('link', { name: 'Back to Norway squad', exact: true })).toBeVisible() + await page.getByRole('link', { name: 'Norway national team', exact: true }).click() + await page.reload() + await page.getByRole('link', { name: 'Back to Erling Haaland', exact: true }).click() + await page.getByRole('link', { name: 'Back to Norway squad', exact: true }).click() + await page.getByRole('link', { name: 'All teams', exact: true }).click() + await expect(page).toHaveURL(/\/teams\?search=nor$/) + await expect(page.locator('.team-card')).toHaveCount(1) + await page.goto('/project2/standings?group=A') + await page.getByRole('table', { name: 'Group A', exact: true }).getByRole('link').first().click() + await page.reload() + await page.getByRole('link', { name: 'Back to standings', exact: true }).click() + await expect(page).toHaveURL(/\/standings\?group=A$/) + await page.goto('/project2/knockout') + await page.locator('.knockout-match').first().getByRole('link').first().click() + await page.reload() + await page.getByRole('link', { name: 'Back to knockout', exact: true }).click() + await expect(page).toHaveURL(/\/knockout$/) + // My Ratings must retain its own sort/page rather than opening the player catalog. + await page.goto('/project2/players/737066') + await page.getByRole('radio', { name: '4 stars', exact: true }).focus() + await page.keyboard.press('Space') + await page.getByRole('button', { name: 'Save rating', exact: true }).click() + await expect(page.getByText('Rating saved.', { exact: true })).toBeVisible() + await page.goto('/project2/my-ratings?sort=NAME_ASC') + await page.getByRole('link', { name: 'Erling Haaland', exact: true }).click() + await page.reload() + await page.getByRole('link', { name: 'Back to My Ratings', exact: true }).click() + await expect(page).toHaveURL(/\/my-ratings\?sort=NAME_ASC$/) +}) diff --git a/frontend/index.html b/frontend/index.html index 4c806ac..177fcc2 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -4,7 +4,7 @@ - VM26 – World Cup 2026 + WC26 – World Cup 2026
diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 7eed915..a60e4a5 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -18,6 +18,7 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", + "@playwright/test": "^1.64.1", "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.3.3", "@testing-library/user-event": "^14.6.8", @@ -37,6 +38,9 @@ "typescript-eslint": "^8.71.1", "vite": "^8.3.0", "vitest": "^5.0.5" + }, + "engines": { + "node": ">=22.22.0" } }, "node_modules/@adobe/css-tools": { @@ -165,7 +169,6 @@ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", @@ -510,7 +513,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=20.19.0" }, @@ -559,7 +561,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=20.19.0" } @@ -869,6 +870,22 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@playwright/test": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@remix-run/route-pattern": { "version": "0.22.1", "resolved": "https://registry.npmjs.org/@remix-run/route-pattern/-/route-pattern-0.22.1.tgz", @@ -1241,7 +1258,8 @@ "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@types/chai": { "version": "5.2.3", @@ -1288,7 +1306,6 @@ "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } @@ -1299,7 +1316,6 @@ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "csstype": "^3.2.2" } @@ -1310,7 +1326,6 @@ "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==", "dev": true, "license": "MIT", - "peer": true, "peerDependencies": { "@types/react": "^19.3.0" } @@ -1360,7 +1375,6 @@ "integrity": "sha512-oM/5sAqz/l1v/zYK1qTOPrn2+JIrBGC1V6uNYucRO5gh6eT9vWJ/RhPbGE59byvZEUQ4VP6XkLBaS5Jti5jpvw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.71.1", "@typescript-eslint/types": "8.71.1", @@ -1681,7 +1695,6 @@ "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -1722,6 +1735,7 @@ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" } @@ -1732,6 +1746,7 @@ "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=10" }, @@ -1835,7 +1850,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.11.26", "caniuse-lite": "^1.0.30001813", @@ -2022,7 +2036,8 @@ "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/electron-to-chromium": { "version": "1.5.452", @@ -2080,7 +2095,6 @@ "integrity": "sha512-npHjrHb2o4ehH3mE+YuxABR+0gyb0aVWCIolgJDArwCiHEIsonBm3ZKjel5b0U5+a+MbEvIyRCGCzD3eKKK2NA==", "dev": true, "license": "MIT", - "peer": true, "workspaces": [ "packages/*" ], @@ -2443,7 +2457,6 @@ "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz", "integrity": "sha512-Chq1s4CY7jmh8gO2qvLIJyfCDIN+EHLFW/9iShnp1z8FjBQMoodWP1kDC36VAMXXIvAjj4ARa7ntfAV2BrjsbA==", "license": "MIT", - "peer": true, "engines": { "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } @@ -2684,7 +2697,6 @@ "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@keyv/serialize": "^1.1.1" } @@ -2996,6 +3008,7 @@ "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", "dev": true, "license": "MIT", + "peer": true, "bin": { "lz-string": "bin/bin.js" } @@ -3215,6 +3228,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/postcss": { "version": "8.5.29", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", @@ -3276,6 +3318,7 @@ "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "ansi-regex": "^5.0.1", "ansi-styles": "^5.0.0", @@ -3320,7 +3363,6 @@ "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -3330,7 +3372,6 @@ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz", "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", "license": "MIT", - "peer": true, "dependencies": { "scheduler": "^0.28.0" }, @@ -3343,7 +3384,8 @@ "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/react-router": { "version": "8.4.0", @@ -3430,7 +3472,6 @@ "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", "license": "Apache-2.0", - "peer": true, "dependencies": { "tslib": "^2.1.0" } @@ -3645,7 +3686,6 @@ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -3742,7 +3782,6 @@ "integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", @@ -3821,7 +3860,6 @@ "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.5", @@ -4029,7 +4067,6 @@ "integrity": "sha512-4UmzQUF5fxvfcYHlbjBmejU+w+hbDnWFx4aS8kBx7nPBHcO2SqPbpAG8snbdg+Xse4pRefR98hgjFgIMCI/UhA==", "dev": true, "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/frontend/package.json b/frontend/package.json index 8517c96..733d53e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -13,7 +13,10 @@ "test": "vitest run", "test:watch": "vitest", "measure:transfer": "MEASURE_TRANSFER=1 vitest run src/test/transfer.test.ts", - "measure:assets": "npm run build && node scripts/measure-assets.mjs" + "measure:assets": "npm run build && node scripts/measure-assets.mjs", + "test:e2e": "playwright test", + "test:e2e:install": "playwright install chromium", + "typecheck:e2e": "tsc --noEmit --project tsconfig.e2e.json" }, "dependencies": { "@apollo/client": "^4.3.5", @@ -26,6 +29,7 @@ }, "devDependencies": { "@eslint/js": "^10.0.1", + "@playwright/test": "^1.64.1", "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.3.3", "@testing-library/user-event": "^14.6.8", @@ -45,5 +49,8 @@ "typescript-eslint": "^8.71.1", "vite": "^8.3.0", "vitest": "^5.0.5" + }, + "engines": { + "node": ">=22.22.0" } } diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts new file mode 100644 index 0000000..370c56f --- /dev/null +++ b/frontend/playwright.config.ts @@ -0,0 +1,33 @@ +import { defineConfig, devices } from '@playwright/test' + +export default defineConfig({ + testDir: './e2e', + fullyParallel: false, + workers: 1, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + reporter: [['list'], ['html', { open: 'never' }]], + use: { + baseURL: 'http://127.0.0.1:4173', + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], + webServer: [ + { + command: 'npm run build --prefix ../backend && node ../backend/tests/e2e-server.js', + url: 'http://127.0.0.1:3101/', + reuseExistingServer: false, + timeout: 60_000, + gracefulShutdown: { signal: 'SIGTERM', timeout: 10_000 }, + }, + { + command: 'npm run build && npm run preview -- --host 127.0.0.1 --port 4173 --strictPort', + url: 'http://127.0.0.1:4173/project2/', + env: { BACKEND_URL: 'http://127.0.0.1:3101', VITE_GRAPHQL_URL: '/project2/graphql' }, + reuseExistingServer: false, + timeout: 60_000, + gracefulShutdown: { signal: 'SIGTERM', timeout: 10_000 }, + }, + ], +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 245e20b..8a2e33d 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,55 +1,25 @@ -import { useEffect, useRef, useState, type MouseEvent } from 'react' -import { - Outlet, - ScrollRestoration, - useLocation, - useMatch, - useNavigationType, - type To, -} from 'react-router' +import { useEffect, useRef, type MouseEvent } from 'react' +import { Outlet, ScrollRestoration, useLocation } from 'react-router' import Header from './components/Header/Header' -/** Values the layout shares with the pages it renders (read with useOutletContext). */ -export type LayoutContext = { - /** Link to the Teams page with the search and filters the user last used there. */ - teamsLink: To -} - /** * Layout shared by every page: skip link, header, main content and the * behaviour that makes client-side navigation feel like normal page loads. */ function App() { const location = useLocation() - const navigationType = useNavigationType() - const onTeamsPage = useMatch('/teams') !== null const mainRef = useRef(null) - // Remember the Teams page's search and filters (its query string), so the - // header link and the "All teams" link on a squad page lead back to the same - // view. Updating state while rendering is React's recommended way to follow - // a value that comes from outside (here, the URL). - const [teamsSearch, setTeamsSearch] = useState(onTeamsPage ? location.search : '') - if (onTeamsPage && location.search !== teamsSearch) setTeamsSearch(location.search) - const teamsLink: To = { pathname: '/teams', search: teamsSearch } - const onPlayersPage = - location.pathname === '/players' || location.pathname.startsWith('/players/') - const [playersSearch, setPlayersSearch] = useState(onPlayersPage ? location.search : '') - if (onPlayersPage && location.search !== playersSearch) setPlayersSearch(location.search) - const playersLink: To = { pathname: '/players', search: playersSearch } - // After moving to another page, put keyboard and screen reader focus on the // new page's main heading, as a full page load would. Changes to the query - // string only (Teams filters) keep focus where it is, and so does the - // initial redirect from / to /teams. + // string only (catalog filters) keep focus where it is. const previousPath = useRef(location.pathname) useEffect(() => { if (previousPath.current === location.pathname) return previousPath.current = location.pathname - if (navigationType === 'REPLACE') return const heading = mainRef.current?.querySelector('h1') ;(heading ?? mainRef.current)?.focus({ preventScroll: true }) - }, [location.pathname, navigationType]) + }, [location.pathname]) function skipToMain(event: MouseEvent) { event.preventDefault() @@ -61,9 +31,9 @@ function App() { Skip to main content -
+
- +
{/* Scrolls to the top on new pages and restores the position on Back/Forward. */} diff --git a/frontend/src/api/teams.ts b/frontend/src/api/teams.ts index cc18635..a5e758a 100644 --- a/frontend/src/api/teams.ts +++ b/frontend/src/api/teams.ts @@ -1,5 +1,5 @@ import { gql, type TypedDocumentNode } from '@apollo/client' -import type { Team, TeamDetails } from '../types/team' +import type { TeamPreview, TeamDetails } from '../types/team' /** Teams per page. The backend allows at most 50 per request. */ export const TEAM_PAGE_SIZE = 12 @@ -11,7 +11,7 @@ export type TeamSort = 'NAME_ASC' | 'NAME_DESC' | 'POINTS_DESC' | 'GOALS_DESC' export type TeamsData = { teamGroups?: string[] - teams: { items: Team[]; totalCount: number; hasNextPage: boolean } + teams: { items: TeamPreview[]; totalCount: number; hasNextPage: boolean } } export type TeamsVariables = { @@ -38,9 +38,8 @@ export const TEAMS_QUERY: TypedDocumentNode = gql` id name group - matches - goals - points + fifaRank + coach } totalCount hasNextPage @@ -70,7 +69,7 @@ export function teamsVariables( export type TeamList = { groups: string[] - items: Team[] + items: TeamPreview[] /** Number of matching teams in the whole result, not just this page. */ totalCount: number hasNextPage: boolean diff --git a/frontend/src/apollo/client.test.tsx b/frontend/src/apollo/client.test.tsx index 322e943..21e7cf4 100644 --- a/frontend/src/apollo/client.test.tsx +++ b/frontend/src/apollo/client.test.tsx @@ -8,21 +8,21 @@ import { renderApp } from '../test/render' import { createApolloClient } from './client' import { evictCatalogLists } from './cacheUpdates' -/** A mutation the tests send to show how the cache reacts. The API has none yet. */ -const UPDATE_POINTS = gql` - mutation UpdatePoints($id: ID!, $points: Int!) { - updateTeam(id: $id, points: $points) { +/** Synthetic team mutation used only to verify Apollo normalization. */ +const UPDATE_COACH = gql` + mutation UpdateCoach($id: ID!, $coach: String!) { + updateTeam(id: $id, coach: $coach) { id - points + coach } } ` -/** The points shown on the card for `team`. */ -function shownPoints(team: string) { +/** The coach shown on the card for `team`. */ +function shownCoach(team: string) { const card = screen.getByRole('heading', { level: 2, name: team }).closest('article')! - const points = within(card).getByText('Points') - return points.nextElementSibling?.textContent + const label = within(card).getByText('Head coach') + return label.nextElementSibling?.textContent } describe('Apollo Client cache', () => { @@ -64,31 +64,29 @@ describe('Apollo Client cache', () => { it('updates every view of a team when a mutation returns it, without a reload', async () => { const { calls } = mockGraphQL((call) => - call.operationName === 'UpdatePoints' - ? graphqlData({ updateTeam: { __typename: 'Team', id: '8492', points: 99 } }) + call.operationName === 'UpdateCoach' + ? graphqlData({ updateTeam: { __typename: 'Team', id: '8492', coach: 'Updated coach' } }) : catalogHandler(call), ) const { client } = renderApp('/teams') await screen.findByText('Showing 1–5 of 5 teams') - expect(shownPoints('Norway')).toBe('6') + expect(shownCoach('Norway')).toBe('Ståle Solbakken') await act(() => - client.mutate({ mutation: UPDATE_POINTS, variables: { id: '8492', points: 99 } }), + client.mutate({ mutation: UPDATE_COACH, variables: { id: '8492', coach: 'Updated coach' } }), ) - expect(shownPoints('Norway')).toBe('99') - expect(calls.map((call) => call.operationName)).toEqual(['Teams', 'UpdatePoints']) + expect(shownCoach('Norway')).toBe('Updated coach') + expect(calls.map((call) => call.operationName)).toEqual(['Teams', 'UpdateCoach']) }) it('requests a shown list again after its cached pages are evicted', async () => { - let norwayPoints = 6 + let norwayCoach = 'Ståle Solbakken' const { calls } = mockGraphQL(() => graphqlData({ teamGroups: ['A', 'C', 'I', 'J'], teams: { - items: TEAMS.map((team) => - team.id === '8492' ? { ...team, points: norwayPoints } : team, - ), + items: TEAMS.map((team) => (team.id === '8492' ? { ...team, coach: norwayCoach } : team)), totalCount: TEAMS.length, hasNextPage: false, }, @@ -98,10 +96,10 @@ describe('Apollo Client cache', () => { await screen.findByText('Showing 1–5 of 5 teams') // Simulates a mutation whose `update` cannot tell how the list changed. - norwayPoints = 12 + norwayCoach = 'New coach' act(() => evictCatalogLists(client.cache)) - await waitFor(() => expect(shownPoints('Norway')).toBe('12')) + await waitFor(() => expect(shownCoach('Norway')).toBe('New coach')) expect(teamsCalls(calls)).toHaveLength(2) }) }) diff --git a/frontend/src/components/DetailNavigation/DetailNavigation.test.tsx b/frontend/src/components/DetailNavigation/DetailNavigation.test.tsx new file mode 100644 index 0000000..3e298ea --- /dev/null +++ b/frontend/src/components/DetailNavigation/DetailNavigation.test.tsx @@ -0,0 +1,77 @@ +import { render, screen } from '@testing-library/react' +import { MemoryRouter } from 'react-router' +import { expect, it } from 'vitest' +import { STAT_FIELDS } from '../../api/players' +import { NORWAY } from '../../test/fixtures' +import { catalogHandler, graphqlData, mockGraphQL, type GraphQLCall } from '../../test/graphql' +import { renderApp } from '../../test/render' +import { DetailBackLink } from './DetailNavigation' + +function handler(call: GraphQLCall) { + if (call.operationName === 'MyRating') return graphqlData({ myRating: null }) + if (call.operationName === 'Player') + return graphqlData({ + player: { + ...NORWAY.players[0], + teamId: NORWAY.id, + country: NORWAY.name, + heightCm: null, + preferredFoot: 'RIGHT', + transferValueEur: null, + statisticsScope: 'WORLD_CUP', + statisticsSeason: '2026', + ...Object.fromEntries(STAT_FIELDS.map((field) => [field, null])), + }, + }) + if (call.operationName === 'Standings') + return graphqlData({ + teamGroups: ['I'], + thirdPlacedTeams: [], + teams: { items: [{ ...NORWAY, goalDifference: 1 }], hasNextPage: false }, + }) + return catalogHandler(call) +} + +it('returns through team/player detail chains to the original filtered catalog', async () => { + mockGraphQL(handler) + const { user, router } = renderApp('/teams?search=nor') + await user.click(await screen.findByRole('link', { name: 'View squad for Norway' })) + await user.click(await screen.findByRole('link', { name: 'Erling Haaland' })) + const teamBack = await screen.findByRole('link', { name: 'Back to Norway squad' }) + expect(teamBack).toHaveAttribute('href', '/teams/8492?search=nor') + await user.click(screen.getByRole('link', { name: 'Norway national team' })) + await user.click(await screen.findByRole('link', { name: 'Back to Erling Haaland' })) + await user.click(await screen.findByRole('link', { name: 'Back to Norway squad' })) + await user.click(await screen.findByRole('link', { name: 'All teams' })) + expect(router.state.location.pathname).toBe('/teams') + expect(router.state.location.search).toBe('?search=nor') + expect(await screen.findByText('Showing 1 of 1 team matching “nor”')).toBeInTheDocument() +}) + +it('returns from a squad to the filtered standings that opened it', async () => { + mockGraphQL(handler) + const { user, router } = renderApp('/standings?group=I') + await user.click(await screen.findByRole('link', { name: 'Norway' })) + await user.click(await screen.findByRole('link', { name: 'Back to standings' })) + expect(router.state.location.pathname).toBe('/standings') + expect(router.state.location.search).toBe('?group=I') + expect(await screen.findByRole('table', { name: 'Group I' })).toBeInTheDocument() +}) + +it('uses a safe catalog fallback for missing or external origin data', () => { + render( + + + , + ) + expect(screen.getByRole('link', { name: 'All players' })).toHaveAttribute('href', '/players') +}) diff --git a/frontend/src/components/DetailNavigation/DetailNavigation.tsx b/frontend/src/components/DetailNavigation/DetailNavigation.tsx new file mode 100644 index 0000000..2af955d --- /dev/null +++ b/frontend/src/components/DetailNavigation/DetailNavigation.tsx @@ -0,0 +1,96 @@ +import { Link, useLocation, useNavigate, type LinkProps } from 'react-router' +import { ArrowLeftIcon } from '../icons/Icons' + +type Origin = { to: string; label: string; parent?: Origin; historyIndex?: number } +const LOCAL_PAGE = + /^\/(?:teams|players)(?:\/[1-9][0-9]*)?(?:[?#].*)?$|^\/(?:standings|knockout|my-ratings|my-xi)(?:[?#].*)?$/ + +/** Only retain app routes and a bounded trail, never arbitrary history-state objects. */ +function readOrigin(value: unknown, depth = 0): Origin | undefined { + if (!value || typeof value !== 'object' || depth >= 12) return + const origin = value as Record + if (typeof origin.to !== 'string' || !LOCAL_PAGE.test(origin.to)) return + if (typeof origin.label !== 'string' || !origin.label || origin.label.length > 160) return + return { + to: origin.to, + label: origin.label, + parent: readOrigin(origin.parent, depth + 1), + historyIndex: Number.isInteger(origin.historyIndex) + ? (origin.historyIndex as number) + : undefined, + } +} + +function originFromState(state: unknown) { + return readOrigin( + state && typeof state === 'object' + ? (state as Record).detailOrigin + : undefined, + ) +} + +const PAGE_LABELS: Record = { + '/teams': 'All teams', + '/players': 'All players', + '/standings': 'Back to standings', + '/knockout': 'Back to knockout', + '/my-ratings': 'Back to My Ratings', + '/my-xi': 'Back to My XI', +} + +/** Detail links carry their source in the browser history entry, which survives refresh. */ +export function DetailLink({ originLabel, ...props }: LinkProps & { originLabel?: string }) { + const location = useLocation() + const label = originLabel ?? PAGE_LABELS[location.pathname] + const origin = label + ? { + to: location.pathname + location.search + location.hash, + label, + parent: originFromState(location.state), + historyIndex: window.history.state?.idx as number | undefined, + } + : undefined + return +} + +/** Explicit return links work without guessing the browser's history depth. */ +export function DetailBackLink({ + fallbackTo, + fallbackLabel, + className, +}: { + fallbackTo: LinkProps['to'] + fallbackLabel: string + className: string +}) { + const location = useLocation() + const origin = originFromState(location.state) + const navigate = useNavigate() + return ( + { + // Use the original history entry when it is still immediately behind us: + // browser scroll restoration and another Back then behave naturally. + if ( + origin?.historyIndex !== undefined && + window.history.state?.idx === origin.historyIndex + 1 && + event.button === 0 && + !event.metaKey && + !event.ctrlKey && + !event.shiftKey && + !event.altKey + ) { + event.preventDefault() + void navigate(-1) + } + }} + > + + {origin?.label ?? fallbackLabel} + + ) +} diff --git a/frontend/src/components/Header/Header.tsx b/frontend/src/components/Header/Header.tsx index a7aabe8..98f7257 100644 --- a/frontend/src/components/Header/Header.tsx +++ b/frontend/src/components/Header/Header.tsx @@ -1,15 +1,9 @@ -import { Link, NavLink, useMatch, type To } from 'react-router' +import { Link, NavLink, useMatch } from 'react-router' import logo from '../../assets/logo.png' import { UserIcon } from '../icons/Icons' import './Header.css' -type HeaderProps = { - /** Link to the Teams page, including the search and filters last used there. */ - teamsLink: To - playersLink: To -} - -function Header({ teamsLink, playersLink }: HeaderProps) { +function Header() { // On a squad page, Teams is the current section but not the current page. const onTeamsList = useMatch('/teams') !== null const onPlayersList = useMatch('/players') !== null @@ -17,10 +11,10 @@ function Header({ teamsLink, playersLink }: HeaderProps) { return (
- + @@ -29,7 +23,7 @@ function Header({ teamsLink, playersLink }: HeaderProps) {
  • {/* Active on /teams and on squad pages under /teams/... */} `header__nav-link${isActive ? ' header__nav-link--active' : ''}` } @@ -50,7 +44,7 @@ function Header({ teamsLink, playersLink }: HeaderProps) {
  • `header__nav-link${isActive ? ' header__nav-link--active' : ''}` @@ -95,7 +89,7 @@ function Header({ teamsLink, playersLink }: HeaderProps) {
    {/* Only one tournament exists, so this is a label, not a control. */}

    - Tournament: VM 2026 + Tournament: WC 2026

    diff --git a/frontend/src/components/TeamCard/TeamCard.css b/frontend/src/components/TeamCard/TeamCard.css index 2253549..0e7a602 100644 --- a/frontend/src/components/TeamCard/TeamCard.css +++ b/frontend/src/components/TeamCard/TeamCard.css @@ -102,34 +102,27 @@ } .team-card__stats { display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 12px; margin: 0; - padding: 15px 8px; + padding: 18px; border-top: 1px solid var(--color-border); } .team-card__stat { - display: flex; - flex-direction: column-reverse; - gap: 3px; - text-align: center; -} -.team-card__stat + .team-card__stat { - border-left: 1px solid var(--color-border); + display: grid; + grid-template-columns: 88px minmax(0, 1fr); + align-items: baseline; + gap: 12px; } .team-card__stat dt { - font-size: 10px; + font-size: 12px; color: var(--color-text-muted); } .team-card__stat dd { margin: 0; - font-size: 21px; - line-height: 1.2; - font-weight: 700; - font-variant-numeric: tabular-nums; - letter-spacing: -0.04em; -} -.team-card__stat:last-child dd { - color: var(--color-primary); + font-size: 13px; + line-height: 1.4; + font-weight: 600; + overflow-wrap: anywhere; } .team-card__button { display: flex; diff --git a/frontend/src/components/TeamCard/TeamCard.test.tsx b/frontend/src/components/TeamCard/TeamCard.test.tsx index 01a83ca..d9ac590 100644 --- a/frontend/src/components/TeamCard/TeamCard.test.tsx +++ b/frontend/src/components/TeamCard/TeamCard.test.tsx @@ -22,15 +22,17 @@ function statValue(label: string) { } describe('TeamCard', () => { - it('shows the team name, group, flag and statistics', () => { + it('shows team identity, FIFA ranking and coach without group-stage totals', () => { renderCard(NORWAY) expect(screen.getByRole('heading', { name: 'Norway' })).toBeInTheDocument() expect(screen.getByText('Group I')).toBeInTheDocument() expect(screen.getByRole('img', { name: 'Flag of Norway' })).toBeInTheDocument() - expect(statValue('Matches')).toBe('3') - expect(statValue('Goals')).toBe('8') - expect(statValue('Points')).toBe('6') + expect(statValue('FIFA ranking')).toBe('#31') + expect(statValue('Head coach')).toBe('Ståle Solbakken') + expect(screen.queryByText('Matches')).not.toBeInTheDocument() + expect(screen.queryByText('Goals')).not.toBeInTheDocument() + expect(screen.queryByText('Points')).not.toBeInTheDocument() }) it('links to the squad page with an accessible name', () => { @@ -40,12 +42,11 @@ describe('TeamCard', () => { expect(link).toHaveAttribute('href', '/teams/8492') }) - it('shows a dash for statistics the dataset does not have', () => { - renderCard({ ...NORWAY, matches: null, goals: null, points: null }) + it('shows a clear fallback when team metadata is missing', () => { + renderCard({ ...NORWAY, fifaRank: null, coach: null }) - expect(statValue('Matches')).toBe('–') - expect(statValue('Goals')).toBe('–') - expect(statValue('Points')).toBe('–') + expect(statValue('FIFA ranking')).toBe('Not available') + expect(statValue('Head coach')).toBe('Not available') }) it('leaves out the flag for an unknown team instead of showing a broken image', () => { diff --git a/frontend/src/components/TeamCard/TeamCard.tsx b/frontend/src/components/TeamCard/TeamCard.tsx index f2d2e91..1bbc849 100644 --- a/frontend/src/components/TeamCard/TeamCard.tsx +++ b/frontend/src/components/TeamCard/TeamCard.tsx @@ -1,15 +1,17 @@ +import { DetailLink } from '../DetailNavigation/DetailNavigation' import type { CSSProperties } from 'react' -import { Link } from 'react-router' +import { useSearchParams } from 'react-router' import { getTeamAppearance } from '../../data/teamAppearance' -import type { Team } from '../../types/team' +import type { TeamPreview } from '../../types/team' import { ArrowRightIcon } from '../icons/Icons' import './TeamCard.css' type TeamCardProps = { - team: Team + team: TeamPreview } function TeamCard({ team }: TeamCardProps) { + const [params] = useSearchParams() const { flagUrl, colors } = getTeamAppearance(team.id) const [primaryColor, secondaryColor] = colors const colorStyle = { @@ -18,9 +20,8 @@ function TeamCard({ team }: TeamCardProps) { } as CSSProperties const stats = [ - { label: 'Matches', value: team.matches }, - { label: 'Goals', value: team.goals }, - { label: 'Points', value: team.points }, + { label: 'FIFA ranking', value: team.fifaRank ? `#${team.fifaRank}` : 'Not available' }, + { label: 'Head coach', value: team.coach || 'Not available' }, ] return ( @@ -59,14 +60,14 @@ function TeamCard({ team }: TeamCardProps) { {/* A link, not a button: it opens another page and can be opened in a new tab. */} - View squad - + ) } diff --git a/frontend/src/components/TeamCard/__snapshots__/TeamCard.test.tsx.snap b/frontend/src/components/TeamCard/__snapshots__/TeamCard.test.tsx.snap index 01982c8..3dcff31 100644 --- a/frontend/src/components/TeamCard/__snapshots__/TeamCard.test.tsx.snap +++ b/frontend/src/components/TeamCard/__snapshots__/TeamCard.test.tsx.snap @@ -44,30 +44,20 @@ exports[`TeamCard > matches the snapshot 1`] = ` class="team-card__stat" >
    - Matches + FIFA ranking
    - 3 + #31
    - Goals + Head coach
    - 8 -
    -
    -
    -
    - Points -
    -
    - 6 + Ståle Solbakken
    diff --git a/frontend/src/components/TeamGrid/TeamGrid.tsx b/frontend/src/components/TeamGrid/TeamGrid.tsx index a9ddbed..de6101c 100644 --- a/frontend/src/components/TeamGrid/TeamGrid.tsx +++ b/frontend/src/components/TeamGrid/TeamGrid.tsx @@ -1,9 +1,9 @@ -import type { Team } from '../../types/team' +import type { TeamPreview } from '../../types/team' import TeamCard from '../TeamCard/TeamCard' import './TeamGrid.css' type TeamGridProps = { - teams: Team[] + teams: TeamPreview[] } function TeamGrid({ teams }: TeamGridProps) { diff --git a/frontend/src/hooks/usePageTitle.ts b/frontend/src/hooks/usePageTitle.ts index 476a5dc..4efef77 100644 --- a/frontend/src/hooks/usePageTitle.ts +++ b/frontend/src/hooks/usePageTitle.ts @@ -2,10 +2,10 @@ import { useEffect } from 'react' /** * Sets the browser tab title for the current page, for example - * "Norway squad – VM26". Screen readers and browser history use it too. + * "Norway squad – WC26". Screen readers and browser history use it too. */ export function usePageTitle(title: string) { useEffect(() => { - document.title = `${title} – VM26` + document.title = `${title} – WC26` }, [title]) } diff --git a/frontend/src/pages/KnockoutPage/KnockoutPage.tsx b/frontend/src/pages/KnockoutPage/KnockoutPage.tsx index 75f51fb..dbcd254 100644 --- a/frontend/src/pages/KnockoutPage/KnockoutPage.tsx +++ b/frontend/src/pages/KnockoutPage/KnockoutPage.tsx @@ -1,3 +1,4 @@ +import { DetailLink } from '../../components/DetailNavigation/DetailNavigation' import { useQuery } from '@apollo/client/react' import { Link } from 'react-router' import { KNOCKOUT_QUERY, type KnockoutMatch, type MatchTeam } from '../../api/knockout' @@ -138,7 +139,7 @@ export default function KnockoutPage() { )}
  • {champion ? ( - {champion.name} + {champion.name} ) : ( To be decided )} @@ -256,7 +257,7 @@ function Participant({ className={`knockout-match__team${winner ? ' knockout-match__team--winner' : decided ? ' knockout-match__team--out' : ''}`} > {team ? ( - + {flag && } {/* The visible code starts the link's accessible name, followed by the full name, as speech input and screen readers expect. */} @@ -265,7 +266,7 @@ function Participant({ {code ? ` ${team.name}` : ''} {winner ? ', winner' : ''} - + ) : ( To be decided diff --git a/frontend/src/pages/MyRatingsPage/MyRatingsPage.test.tsx b/frontend/src/pages/MyRatingsPage/MyRatingsPage.test.tsx index 790d505..3686cdd 100644 --- a/frontend/src/pages/MyRatingsPage/MyRatingsPage.test.tsx +++ b/frontend/src/pages/MyRatingsPage/MyRatingsPage.test.tsx @@ -324,7 +324,7 @@ describe('My Ratings', () => { expect(await screen.findByText('You have not rated any players yet.')).toBeInTheDocument() expect(screen.getByRole('heading', { level: 1, name: 'My Ratings' })).toHaveFocus() - expect(document.title).toBe('My Ratings – VM26') + expect(document.title).toBe('My Ratings – WC26') expect(screen.getByRole('link', { name: 'My Ratings' })).toHaveAttribute('aria-current', 'page') expect(screen.getByRole('link', { name: 'Knockout' })).toHaveAttribute('href', '/knockout') }) @@ -553,3 +553,20 @@ describe('Ratings accessibility', () => { await expectNoAxeViolations() }) }) + +it('does not save a comment-only rating until a star value is chosen', async () => { + const { handler } = ratingsServer() + const { calls } = mockGraphQL(handler) + const { user } = renderApp('/players/1') + const comment = await screen.findByLabelText('Comment (optional)') + await user.type(comment, 'Keep this draft') + const save = screen.getByRole('button', { name: 'Save rating' }) + expect(save).toHaveAttribute('aria-disabled', 'true') + await user.click(save) + expect(calls.filter((call) => call.operationName === 'RatePlayer')).toHaveLength(0) + expect(comment).toHaveValue('Keep this draft') + await user.click(screen.getByRole('radio', { name: /^3 stars$/ })) + await user.click(save) + expect(await screen.findByText('Rating saved.')).toBeInTheDocument() + expect(calls.filter((call) => call.operationName === 'RatePlayer')).toHaveLength(1) +}) diff --git a/frontend/src/pages/MyRatingsPage/MyRatingsPage.tsx b/frontend/src/pages/MyRatingsPage/MyRatingsPage.tsx index a1c82d2..ed2e7e7 100644 --- a/frontend/src/pages/MyRatingsPage/MyRatingsPage.tsx +++ b/frontend/src/pages/MyRatingsPage/MyRatingsPage.tsx @@ -1,3 +1,4 @@ +import { DetailLink } from '../../components/DetailNavigation/DetailNavigation' import { useEffect, useId, useRef, useState } from 'react' import { Link, useSearchParams } from 'react-router' import { useQuery } from '@apollo/client/react' @@ -226,9 +227,9 @@ function RatingItem({ rating, ownerId, onRemoved }: RatingItemProps) {
    {player ? ( - + {name} - + ) : ( {name} (no longer in the catalog) )} diff --git a/frontend/src/pages/MyXIPage/MyXIPage.test.tsx b/frontend/src/pages/MyXIPage/MyXIPage.test.tsx index 3b14f58..fa774f0 100644 --- a/frontend/src/pages/MyXIPage/MyXIPage.test.tsx +++ b/frontend/src/pages/MyXIPage/MyXIPage.test.tsx @@ -478,3 +478,21 @@ describe('My XI accessibility', () => { expect(save).toHaveAttribute('aria-disabled', 'true') }) }) + +it('keeps the selected players and prevents saving an unnamed lineup', async () => { + const { handler } = myXIServer() + const { calls } = mockGraphQL(handler) + const { user } = renderApp('/my-xi') + await screen.findByText('Not saved yet.') + await choosePlayer(user, 'Forward 2', 'haal', HAALAND.name) + await user.clear(screen.getByLabelText('Lineup name')) + const save = screen.getByRole('button', { name: 'Save lineup' }) + expect(save).toHaveAttribute('aria-disabled', 'true') + await user.click(save) + expect(calls.filter((call) => call.operationName === 'SaveLineup')).toHaveLength(0) + expect(within(slot('Forward 2')).getByText(HAALAND.name)).toBeInTheDocument() + await user.type(screen.getByLabelText('Lineup name'), 'Recovered XI') + await user.click(save) + await screen.findByText(/^Saved /) + expect(calls.filter((call) => call.operationName === 'SaveLineup')).toHaveLength(1) +}) diff --git a/frontend/src/pages/NotFoundPage/NotFoundPage.tsx b/frontend/src/pages/NotFoundPage/NotFoundPage.tsx index 6dbe2e8..3f443f8 100644 --- a/frontend/src/pages/NotFoundPage/NotFoundPage.tsx +++ b/frontend/src/pages/NotFoundPage/NotFoundPage.tsx @@ -1,11 +1,9 @@ -import { Link, useOutletContext } from 'react-router' -import type { LayoutContext } from '../../App' +import { Link } from 'react-router' import { usePageTitle } from '../../hooks/usePageTitle' import '../page.css' /** Shown for addresses that do not match any page. */ function NotFoundPage() { - const { teamsLink } = useOutletContext() usePageTitle('Page not found') return ( @@ -15,7 +13,7 @@ function NotFoundPage() {

    This page does not exist, or it is not available yet.

    - + Go to Teams
    diff --git a/frontend/src/pages/PlayerPage/PlayerPage.tsx b/frontend/src/pages/PlayerPage/PlayerPage.tsx index 66d0e9e..da710f2 100644 --- a/frontend/src/pages/PlayerPage/PlayerPage.tsx +++ b/frontend/src/pages/PlayerPage/PlayerPage.tsx @@ -1,11 +1,11 @@ -import { Link, useParams, useSearchParams } from 'react-router' +import { DetailLink, DetailBackLink } from '../../components/DetailNavigation/DetailNavigation' +import { useParams, useSearchParams } from 'react-router' import { useQuery } from '@apollo/client/react' import { PLAYER_QUERY, STAT_FIELDS } from '../../api/players' import { toRequestState } from '../../apollo/requestState' import PlayerPhoto from '../../components/PlayerPhoto/PlayerPhoto' import PlayerRating from '../../components/PlayerRating/PlayerRating' import { getTeamAppearance } from '../../data/teamAppearance' -import { ArrowLeftIcon } from '../../components/icons/Icons' import { formatPosition } from '../../data/players' import { usePageTitle } from '../../hooks/usePageTitle' import { writePlayerFilters } from '../PlayersPage/playerFilters' @@ -37,13 +37,11 @@ export default function PlayerPage() { const catalogParams = writePlayerFilters(params, {}) return (
    - - - All players - + fallbackTo={{ pathname: '/players', search: catalogParams.toString() }} + fallbackLabel="All players" + />
    {player && }
    @@ -52,7 +50,11 @@ export default function PlayerPage() { {title} {player && ( - + {getTeamAppearance(player.teamId).flagUrl && ( )} {player.country} national team - + )}
    {player && ( diff --git a/frontend/src/pages/PlayersPage/PlayersPage.test.tsx b/frontend/src/pages/PlayersPage/PlayersPage.test.tsx index 2f5e380..982890a 100644 --- a/frontend/src/pages/PlayersPage/PlayersPage.test.tsx +++ b/frontend/src/pages/PlayersPage/PlayersPage.test.tsx @@ -60,6 +60,28 @@ function handler({ operationName, variables: v }: GraphQLCall) { } describe('Players catalog', () => { + it('preserves submitted search when filters change before a navigation settles', async () => { + const { calls } = mockGraphQL(handler) + const { router } = renderApp('/players?page=2') + await screen.findByText('Player 13') + fireEvent.change(screen.getByLabelText('Search players'), { target: { value: 'Player' } }) + act(() => { + fireEvent.submit(screen.getByRole('search')) + fireEvent.change(screen.getByLabelText('National team'), { target: { value: '8492' } }) + fireEvent.change(screen.getByLabelText('Sort by'), { target: { value: 'NAME_DESC' } }) + }) + await screen.findByText('Player 25') + expect(router.state.location.search).toBe('?search=Player&teamId=8492&sort=NAME_DESC') + expect( + calls.filter((call) => call.operationName === 'Players').at(-1)?.variables, + ).toMatchObject({ + search: 'Player', + teamId: '8492', + sort: 'NAME_DESC', + offset: 0, + }) + }) + it('loads bounded pages and makes every matching result reachable', async () => { const { calls } = mockGraphQL(handler) const { user, router } = renderApp('/players') diff --git a/frontend/src/pages/PlayersPage/PlayersPage.tsx b/frontend/src/pages/PlayersPage/PlayersPage.tsx index f36a4de..d40b8da 100644 --- a/frontend/src/pages/PlayersPage/PlayersPage.tsx +++ b/frontend/src/pages/PlayersPage/PlayersPage.tsx @@ -1,5 +1,6 @@ +import { DetailLink } from '../../components/DetailNavigation/DetailNavigation' import { useEffect, useRef, useState, type FormEvent } from 'react' -import { Link, useSearchParams } from 'react-router' +import { useSearchParams } from 'react-router' import { useQuery } from '@apollo/client/react' import { PLAYERS_QUERY, @@ -58,8 +59,9 @@ export default function PlayersPage() { summaryRef.current?.focus() focusSummary.current = false }, [state]) + // Commit URL changes before another control event can read the previous filters. const update = (changes: Partial) => - setParams((current) => writePlayerFilters(current, changes)) + setParams((current) => writePlayerFilters(current, changes), { flushSync: true }) const retry = () => { result.refetch().catch(() => {}) } @@ -159,7 +161,7 @@ export default function PlayersPage() { {state.data.players.items.length ? (
    {state.data.players.items.map((player) => ( - View player - + ))}
    ) : ( diff --git a/frontend/src/pages/StandingsPage/StandingsPage.test.tsx b/frontend/src/pages/StandingsPage/StandingsPage.test.tsx index 5bf9d4f..18103cb 100644 --- a/frontend/src/pages/StandingsPage/StandingsPage.test.tsx +++ b/frontend/src/pages/StandingsPage/StandingsPage.test.tsx @@ -68,19 +68,19 @@ function standingsResponse(group: unknown) { } describe('Standings', () => { - it('provides a collapsed, accessible explanation of ranking and source limitations', async () => { + it('provides a collapsed, accessible explanation of ranking', async () => { mockGraphQL((call) => standingsResponse(call.variables.group)) const { user } = renderApp('/standings') await screen.findByRole('table', { name: 'Group A' }) const summary = screen.getByText('How ranking works') const details = summary.closest('details')! expect(details).not.toHaveAttribute('open') - expect(within(details).getByText(/Earlier ranking editions/)).not.toBeVisible() + expect(screen.queryByText(/Data limitations/)).not.toBeInTheDocument() await user.click(summary) expect(details).toHaveAttribute('open') expect(within(details).getByText(/head-to-head points/)).toBeVisible() expect(within(details).getByText(/the group filter does not affect/)).toBeVisible() - expect(within(details).getByText(/not an official tie-break/)).toBeVisible() + expect(screen.queryByText(/Earlier ranking editions/)).not.toBeInTheDocument() await user.click(summary) expect(details).not.toHaveAttribute('open') }) diff --git a/frontend/src/pages/StandingsPage/StandingsPage.tsx b/frontend/src/pages/StandingsPage/StandingsPage.tsx index 5a7c820..18a0eb8 100644 --- a/frontend/src/pages/StandingsPage/StandingsPage.tsx +++ b/frontend/src/pages/StandingsPage/StandingsPage.tsx @@ -1,4 +1,5 @@ -import { Link, useSearchParams } from 'react-router' +import { DetailLink } from '../../components/DetailNavigation/DetailNavigation' +import { useSearchParams } from 'react-router' import SelectField from '../../components/SelectField/SelectField' import { getTeamAppearance } from '../../data/teamAppearance' import { usePageTitle } from '../../hooks/usePageTitle' @@ -81,12 +82,6 @@ export default function StandingsPage() { goal difference, goals scored, fair play and FIFA ranking. The best eight qualify; the group filter does not affect this table. A higher fair-play score is better.

    -

    - Data limitations. Calculations use group-stage card events from the - source, including officials when reported, and the 11 June 2026 FIFA ranking. Earlier - ranking editions are not imported. If a tie remains, name and source ID give a stable - display order, not an official tie-break. Missing statistics appear as –. -

    {state.status === 'loading' && ( @@ -201,7 +196,7 @@ function GroupTable({ > {index + 1} - + {flagUrl && ( )} {team.name} - + {columns.map(([field]) => ( {team[field] ?? '–'} diff --git a/frontend/src/pages/TeamPage/TeamPage.test.tsx b/frontend/src/pages/TeamPage/TeamPage.test.tsx index f683130..b810f7c 100644 --- a/frontend/src/pages/TeamPage/TeamPage.test.tsx +++ b/frontend/src/pages/TeamPage/TeamPage.test.tsx @@ -6,6 +6,17 @@ import { renderApp } from '../../test/render' import { expectNoAxeViolations } from '../../test/axe' describe('Squad page', () => { + it('keeps the explicit return filters after a direct detail load or refresh', async () => { + mockGraphQL() + renderApp('/teams/8492?search=nor&group=I&sort=POINTS_DESC&page=2') + await screen.findByRole('heading', { level: 1, name: 'Norway' }) + expect(screen.getByRole('link', { name: 'All teams' })).toHaveAttribute( + 'href', + '/teams?search=nor&group=I&sort=POINTS_DESC&page=2', + ) + expect(screen.getByRole('link', { name: /^Teams$/ })).toHaveAttribute('href', '/teams') + }) + it('shows the team and its squad grouped by line', async () => { const { calls } = mockGraphQL() renderApp('/teams/8492') diff --git a/frontend/src/pages/TeamPage/TeamPage.tsx b/frontend/src/pages/TeamPage/TeamPage.tsx index 9100a04..b161eec 100644 --- a/frontend/src/pages/TeamPage/TeamPage.tsx +++ b/frontend/src/pages/TeamPage/TeamPage.tsx @@ -1,8 +1,8 @@ +import { DetailLink, DetailBackLink } from '../../components/DetailNavigation/DetailNavigation' import type { CSSProperties } from 'react' import PlayerPhoto from '../../components/PlayerPhoto/PlayerPhoto' -import { Link, useOutletContext, useParams } from 'react-router' -import type { LayoutContext } from '../../App' -import { ArrowLeftIcon } from '../../components/icons/Icons' +import { Link, useSearchParams, useParams } from 'react-router' +import { writeTeamFilters } from '../TeamsPage/teamFilters' import { ageOn, formatPosition, groupByLine } from '../../data/players' import { getTeamAppearance } from '../../data/teamAppearance' import { usePageTitle } from '../../hooks/usePageTitle' @@ -18,7 +18,8 @@ import './TeamPage.css' */ function TeamPage() { const { teamId = '' } = useParams() - const { teamsLink } = useOutletContext() + const [params] = useSearchParams() + const teamsLink = { pathname: '/teams', search: writeTeamFilters(params, {}).toString() } const { state, retry } = useTeam(teamId) const retryWithFocus = useRetryFocus(state.status === 'success') @@ -45,10 +46,11 @@ function TeamPage() { return (
    - - - All teams - + {/* The heading stays the same element in every state, so focus placed on it after navigation is kept when the content arrives. */} @@ -166,7 +168,12 @@ function TeamDetailsContent({ team }: { team: TeamDetails }) { - {player.name} + + {player.name} + {formatPosition(player.position)} diff --git a/frontend/src/pages/TeamsPage/TeamsPage.test.tsx b/frontend/src/pages/TeamsPage/TeamsPage.test.tsx index 67ae522..701e484 100644 --- a/frontend/src/pages/TeamsPage/TeamsPage.test.tsx +++ b/frontend/src/pages/TeamsPage/TeamsPage.test.tsx @@ -1,4 +1,4 @@ -import { act, screen, waitFor, within } from '@testing-library/react' +import { act, fireEvent, screen, waitFor, within } from '@testing-library/react' import { describe, expect, it } from 'vitest' import { catalogHandler, @@ -24,6 +24,28 @@ async function waitForTeams() { } describe('Teams page', () => { + it('composes rapid search, group and sort changes without losing URL filters', async () => { + const { calls } = mockGraphQL() + const { router } = renderApp('/teams') + await waitForTeams() + fireEvent.change(screen.getByLabelText('Search for national teams'), { + target: { value: 'south' }, + }) + act(() => { + fireEvent.submit(screen.getByRole('search')) + fireEvent.change(screen.getByLabelText('Group'), { target: { value: 'A' } }) + fireEvent.change(screen.getByLabelText('Sort by'), { target: { value: 'POINTS_DESC' } }) + }) + await waitFor(() => expect(shownTeams()).toEqual(['South Africa', 'South Korea'])) + expect(router.state.location.search).toBe('?search=south&group=A&sort=POINTS_DESC') + expect(teamsCalls(calls).at(-1)?.variables).toMatchObject({ + search: 'south', + group: 'A', + sort: 'POINTS_DESC', + offset: 0, + }) + }) + it('shows a loading message and then the teams from GraphQL', async () => { const pending = deferred() const { calls } = mockGraphQL(() => pending.promise) @@ -242,6 +264,23 @@ function pageButton(name: 'First page' | 'Previous page' | 'Next page' | 'Last p } describe('Teams pagination', () => { + it('opens a fresh catalog from the menu while browser Back restores the old page', async () => { + mockGraphQL(catalogHandlerFor(MANY_TEAMS)) + const { user, router } = renderApp('/teams?page=2') + await screen.findByText('Showing 13–24 of 30 teams') + await user.click(screen.getByRole('link', { name: /^My XI$/ })) + await screen.findByRole('heading', { level: 1, name: 'My XI' }) + await user.click(screen.getByRole('link', { name: /^Teams$/ })) + await screen.findByText('Showing 1–12 of 30 teams') + expect(router.state.location.search).toBe('') + expect(screen.getByRole('link', { name: 'WC26, go to Teams' })).toHaveAttribute( + 'href', + '/teams', + ) + await act(() => router.navigate(-2)) + await screen.findByText('Showing 13–24 of 30 teams') + }) + it('pages through all results, with a partially filled last page', async () => { const { calls } = mockGraphQL(catalogHandlerFor(MANY_TEAMS)) const { user, router } = renderApp('/teams') @@ -364,7 +403,7 @@ describe('Teams accessibility', () => { await expectNoAxeViolations() // The tournament is a label, not a control that does nothing. expect(screen.queryByRole('combobox', { name: /Tournament/ })).not.toBeInTheDocument() - expect(screen.getByText('VM 2026')).toBeInTheDocument() + expect(screen.getByText('WC 2026')).toBeInTheDocument() }) it('moves focus to the main heading when Try again succeeds', async () => { diff --git a/frontend/src/pages/TeamsPage/TeamsPage.tsx b/frontend/src/pages/TeamsPage/TeamsPage.tsx index b19b9ea..bfb6744 100644 --- a/frontend/src/pages/TeamsPage/TeamsPage.tsx +++ b/frontend/src/pages/TeamsPage/TeamsPage.tsx @@ -15,8 +15,8 @@ import './TeamsPage.css' const SORT_OPTIONS = [ { value: 'NAME_ASC', label: 'A-Z' }, { value: 'NAME_DESC', label: 'Z-A' }, - { value: 'POINTS_DESC', label: 'Most points' }, - { value: 'GOALS_DESC', label: 'Most goals' }, + { value: 'POINTS_DESC', label: 'Group-stage points' }, + { value: 'GOALS_DESC', label: 'Group-stage goals' }, ] function teamCount(count: number) { @@ -67,8 +67,12 @@ function TeamsPage() { // Filter changes replace the current history entry instead of adding one, // so Back leaves the Teams page instead of stepping through every change. + // Flush the URL update so rapid control changes compose with the latest filters. function updateFilters(changes: Partial) { - setSearchParams((current) => writeTeamFilters(current, changes), { replace: true }) + setSearchParams((current) => writeTeamFilters(current, changes), { + replace: true, + flushSync: true, + }) } // Moving to another page adds a history entry, so Back returns to the diff --git a/frontend/src/styles/index.css b/frontend/src/styles/index.css index bf7aa31..d8fe037 100644 --- a/frontend/src/styles/index.css +++ b/frontend/src/styles/index.css @@ -30,9 +30,9 @@ select { outline-offset: 2px; } -/* Headings and
    receive focus after navigation (tabindex="-1"). They are - not interactive, so they only get an outline when focus came from the keyboard. */ -[tabindex='-1']:focus:not(:focus-visible) { +/* Programmatic focus announces navigation without drawing a box around text. + Interactive links, buttons and inputs keep their visible keyboard focus above. */ +[tabindex='-1']:focus { outline: none; } diff --git a/frontend/src/test/fixtures.ts b/frontend/src/test/fixtures.ts index 33e5e98..76844a5 100644 --- a/frontend/src/test/fixtures.ts +++ b/frontend/src/test/fixtures.ts @@ -7,7 +7,16 @@ import type { Team, TeamDetails } from '../types/team' export const TEAMS: Team[] = [ { id: '6706', name: 'Argentina', group: 'J', matches: 3, goals: 8, points: 9 }, { id: '8256', name: 'Brazil', group: 'C', matches: 3, goals: 7, points: 7 }, - { id: '8492', name: 'Norway', group: 'I', matches: 3, goals: 8, points: 6 }, + { + id: '8492', + name: 'Norway', + fifaRank: 31, + coach: 'Ståle Solbakken', + group: 'I', + matches: 3, + goals: 8, + points: 6, + }, { id: '6316', name: 'South Africa', group: 'A', matches: 3, goals: 2, points: 4 }, { id: '7804', name: 'South Korea', group: 'A', matches: 3, goals: 2, points: 3 }, ] diff --git a/frontend/src/test/graphql.ts b/frontend/src/test/graphql.ts index d74bb60..6826d4c 100644 --- a/frontend/src/test/graphql.ts +++ b/frontend/src/test/graphql.ts @@ -48,6 +48,12 @@ function withTypenames(value: unknown, typename: string): unknown { const fields = FIELD_TYPES[typename] ?? {} return Object.fromEntries([ ...(typename === 'Query' ? [] : [['__typename', typename]]), + ...(typename === 'Team' + ? [ + ['fifaRank', null], + ['coach', null], + ] + : []), ...Object.entries(value).map(([key, child]) => [ key, key in fields ? withTypenames(child, fields[key]) : child, diff --git a/frontend/src/test/render.tsx b/frontend/src/test/render.tsx index 0dd0c63..05617b6 100644 --- a/frontend/src/test/render.tsx +++ b/frontend/src/test/render.tsx @@ -1,7 +1,8 @@ import { render } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { ApolloProvider } from '@apollo/client/react' -import { createMemoryRouter, RouterProvider } from 'react-router' +import { createMemoryRouter } from 'react-router' +import { RouterProvider } from 'react-router/dom' import { createApolloClient } from '../apollo/client' import { routes } from '../router' diff --git a/frontend/src/types/team.ts b/frontend/src/types/team.ts index bb0495d..c23492d 100644 --- a/frontend/src/types/team.ts +++ b/frontend/src/types/team.ts @@ -1,5 +1,14 @@ +/** Lightweight team fields used by catalog cards; no group-stage totals. */ +export interface TeamPreview { + id: string + name: string + group: string + fifaRank?: number | null + coach?: string | null +} + /** A national team as returned by the GraphQL API. */ -export interface Team { +export interface Team extends TeamPreview { /** Stable ID from the source dataset, for example "8492" for Norway. */ id: string name: string diff --git a/frontend/tsconfig.e2e.json b/frontend/tsconfig.e2e.json new file mode 100644 index 0000000..8c068f7 --- /dev/null +++ b/frontend/tsconfig.e2e.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["e2e/**/*.ts", "playwright.config.ts"] +} diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index d491475..03c7598 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -29,6 +29,7 @@ export default defineConfig(({ mode }) => { server: { proxy }, preview: { proxy }, test: { + include: ['src/**/*.test.{ts,tsx}'], // Components are tested in a simulated browser. GraphQL responses are // mocked in each test (see src/test/graphql.ts), so no backend is needed. environment: 'jsdom',