diff --git a/.gitignore b/.gitignore index 5a05918..57f7df2 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,9 @@ dist-ssr # Local Claude Code settings .claude/ + +# Playwright and coverage +test-results/ +playwright-report/ +blob-report/ +coverage/ diff --git a/README.md b/README.md index 674a0fd..60d65f8 100644 --- a/README.md +++ b/README.md @@ -56,10 +56,10 @@ yet, depending on when the review is made. | Filtering and sorting in the user interface | Done | Filter panel, active filters and sorting on `/sok` | | Wine detail page | Done | Facts, food pairing, the shared average, the rating distribution and student reviews at `/vin/:id` | | Student reviews (stored in the database) | Done | 0.5–5 stars and an optional comment, saved and shown at once on the wine page. They count in the shared average | -| «Mine anmeldelser» page | Done | Shows the user's «Vil prøve» list from the API, behind login. Own reviews come with the profile page | +| «Min side» (profile) | Done | The top 4 in its own frame, the newest wines on each list with «Se alle», and the newest reviews, behind login. A page for each list, and for all reviews (newest or oldest first) | | User accounts | Done | Register, log in and log out at `/konto`, with sessions in PostgreSQL and an `httpOnly` cookie | | Reviews tied to accounts | Done | Writing a review requires login, and the username is shown as the author. Older anonymous reviews are kept as «Anonym student» | -| Favourites, top 4, «Vil prøve» and «Har prøvd» per user | Done | Heart and bookmark on the wine cards, all three on the wine page. Choosing the top 4 comes with the profile page. See [API](docs/api.md#wine-lists) | +| Favourites, top 4, «Vil prøve» and «Har prøvd» per user | Done | Heart and bookmark on the wine cards, all three on the wine page, and «Endre topp 4» on «Min side». See [API](docs/api.md#wine-lists) | | Demo user for testing | Done | `demo` / `kork-og-krone`, see [Demo user](#demo-user) | | Larger dataset on the VM | Done | Full version: 100 646 wines and 21 013 536 ratings | | Continuous integration (CI) | Not yet started | Needs a self-hosted runner | @@ -131,8 +131,9 @@ This section describes what users can do. "Backend" means the API supports the f | Wine detail page | Done (`wine(id)`) | Done | Name, winery, region, grapes, alcohol, body, acidity, vintages and food pairing in Norwegian. Grapes and food link to the search | | Student reviews | Done | Done | 0.5–5 stars in half stars and an optional comment, stored in PostgreSQL. Hover the left half of a star for half a star, or use the arrow keys. The page updates at once without a reload. One review per student per wine | | Shared average and distribution | Done | Done | Student reviews count in the average together with X-Wines, also when sorting and filtering. The wine page shows how many gave each score | -| Wine lists: favourite, «Vil prøve» and «Har prøvd» | Done | Done | Stored per user and public, so they follow the user between browsers. Heart and bookmark on the wine cards, all three on the wine page, and «Vil prøve» on «Mine anmeldelser». The buttons change at once and go back with a message if saving fails. Visitors are sent to log in and back. «Har prøvd» takes a wine off «Vil prøve», and a saved review marks the wine as tried. A «Vil prøve» list from before login moves to the user once. See [API](docs/api.md#wine-lists) | -| Top 4 favourites | Done | Planned | `setTopFavourites` and `topFavourites` in the API. Choosing them comes with the profile page | +| Wine lists: favourite, «Vil prøve» and «Har prøvd» | Done | Done | Stored per user and public, so they follow the user between browsers. Heart and bookmark on the wine cards, all three on the wine page, and each list on «Min side». The buttons change at once and go back with a message if saving fails. Visitors are sent to log in and back. «Har prøvd» takes a wine off «Vil prøve», and a saved review marks the wine as tried. A «Vil prøve» list from before login moves to the user once. See [API](docs/api.md#wine-lists) | +| Top 4 favourites | Done | Done | Shown in its own frame on «Min side», with four numbered places. «Endre topp 4» chooses and orders them with buttons that work with the keyboard and a screen reader, without drag and drop | +| «Min side» | Done | Done | `/mine` with the top 4, the lists and the reviews, a page for each list at `/mine/favoritter`, `/mine/vil-prove` and `/mine/har-provd`, and `/mine/dommer`, newest or oldest first. Behind login | | User accounts | Done | Done | Register, log in and log out at `/konto`. Errors are shown next to the field they are about, in Norwegian. Sessions in PostgreSQL with an `httpOnly` cookie | | Reviews with login | Done | Done | Only logged-in users can write, change or delete a review, and only their own. Visitors see the reviews and a link to log in, which brings them back to the wine. `User.reviews` lists a user's reviews for the profile page | @@ -166,6 +167,7 @@ Each row explains what we chose, why, and what else we considered. Added as the | Search, filtering and sorting | In the database | Scales to large datasets. The frontend never loads the whole catalogue | Filtering in the browser | | Rating average | Stored on the wine and recalculated when a review is saved or deleted | Sorting and filtering by rating never has to count millions of rows | Calculating the average for every query | | List buttons | `myLists` asked for with each wine, read from the cache with `useFragment`, and changed with an optimistic answer | A page of wines needs no extra request, every button for a wine agrees, and a click shows at once | Fetching the lists of each wine separately, or waiting for the API before the button changes | +| Top 4 editor | Buttons to move, add and take out, with a live region and focus kept on the button | Works the same with a keyboard, a screen reader, a switch and a finger, and is simple to test | Drag and drop, which needs a second way to do the same for keyboard and screen reader users | | Expired session | An Apollo link that fetches `me` again when the API says `UNAUTHENTICATED` | The whole page shows at once that the user is logged out, wherever the error came from | Checking for the error in each feature | | Batched lookups | DataLoader for reviews and ratings per wine | A page of wines runs one query per field instead of one per wine (the N+1 problem) | One query per wine | | Search state flow | Field text in React state, debounced into the URL, and the query reads only the URL | One source of truth for the search, so reload, shared links and the back button all give the same result | Sending a request directly from the input | @@ -242,8 +244,10 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing, - Ratings are always shown as text, for example "4,6 av 5 · 23 dommer". The stars have a text alternative, so a screen reader reads «3,5 av 5 stjerner» instead of five images. - Giving a review works with the keyboard: the stars are radio buttons, so the arrow keys move through every half star, and each half is at least 24 × 24 px to click (WCAG 2.5.8). - Loading states are announced in a live region. Errors use `role="alert"` and have a "Prøv igjen" button. The message after saving a review stays in the same live region, so it is announced. -- Click targets are at least 44 × 44 px. +- Click targets are at least 44 × 44 px. The heart and the bookmark on the wine cards are 44 × 40 px, so they sit closer together; that is still well above the 24 px WCAG 2.5.8 asks for. - The list buttons are toggle buttons (`aria-pressed`). On the wine page they have visible text in a named group. On the cards they are icons, with the wine's name in the accessible name («Favoritt Origem Merlot»). A pressed button gets a filled icon and a background, so the state does not rest on colour alone. +- «Endre topp 4» uses buttons only, no drag and drop: «Flytt opp», «Flytt ned», «Ta ut» and «Legg til», named with the wine. Each change is read out, focus never jumps to the top of the page, and a button that does nothing right now (`aria-disabled`) can still have focus. +- When a wine disappears from a list on «Min side», a live region says so and focus moves to the list's heading. - Animations respect `prefers-reduced-motion`. - No horizontal scrolling at 320 px width (WCAG 1.4.10, reflow). - Text contrast is at least 4.9:1 in both light and dark mode. @@ -306,9 +310,9 @@ and because the test was run over VPN. These are the "before" numbers. Compressi | Level | Tools | What we test | Number of tests | |---|---|---|---| -| Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, mapping of API data, data hooks, components, the landing page, the wine page with reviews, the list buttons and «Mine anmeldelser», the cache rules for the lists, an expired session, loading, empty and error states, and axe on each component | 373 in 42 files | -| Unit (backend) | Vitest | Parsing of X-Wines CSV files, building SQL for search, filtering and sorting, review validation, and passwords, sessions and rate limiting | 92 in 11 files (6 skipped: they need a test database) | -| End-to-end | Playwright with axe-core, desktop and mobile | Landing, search and detail pages with a stubbed API: one request per page load, debounce, search, filters, sorting, load more, reload, back button, from search to wine and back, the filter dialog on mobile, no hits, wine not found, API errors, keyboard use, reflow at 320 px, the wine lists (also after a reload, with login on the way, and the move of an old list), and no axe violations (WCAG 2.1 AA) | 82 (2 skipped) | +| Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, mapping of API data, data hooks, components, the landing page, the wine page with reviews, the list buttons, «Min side», the list pages, the reviews page and «Endre topp 4», the cache rules for the lists, an expired session, loading, empty and error states, and axe on each component | 421 in 46 files | +| Unit (backend) | Vitest | Parsing of X-Wines CSV files, building SQL for search, filtering and sorting, review validation, and passwords, sessions and rate limiting | 147 in 17 files (42 tests, 4 files skipped: they need a test database) | +| End-to-end | Playwright with axe-core, desktop and mobile | Landing, search and detail pages with a stubbed API: one request per page load, debounce, search, filters, sorting, load more, reload, back button, from search to wine and back, the filter dialog on mobile, no hits, wine not found, API errors, keyboard use, reflow at 320 px, the wine lists (also after a reload, with login on the way, and the move of an old list), «Min side» from login to logout with the top 4 chosen with the keyboard, and no axe violations (WCAG 2.1 AA) | 86 (2 skipped) | | API | Vitest with Apollo Server (`executeOperation`) | Login, reviews, wine lists, the top 4 and the demo user through real GraphQL requests, with a fake browser per user that keeps the cookie. The review tests run against a separate test database (`TEST_DATABASE_URL`), see [API](docs/api.md#database-tests) | Count again | Counted on 16 November 2026. The skipped backend tests run the user store against a real database, and need `TEST_DATABASE_URL`. @@ -401,7 +405,7 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a - [x] Login in the interface: forms for register and login, and reviews tied to the account instead of the anonymous ID. - [x] Favourites with a top 4, «Vil prøve» and «Har prøvd» stored per user (backend and API). - [x] The lists in the interface: heart, bookmark and «Har prøvd» on the wines. -- [ ] Profile page with the top 4, the lists and the user's reviews. +- [x] Profile page («Min side») with the top 4, the lists and the user's reviews. - [x] Wishlist stored in the backend, so it follows the user between devices. - [ ] Calmer landing page: less text, a separate «Om» page, and a burger menu on mobile. - [ ] CI, an enforced coverage threshold, and eslint-plugin-jsx-a11y. @@ -415,7 +419,7 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a - [x] Wine detail page. - [x] Student reviews: GraphQL mutation, database tables, validation, and the new rating shown at once. - [x] Half stars, a shared average and the rating distribution. -- [x] «Mine anmeldelser» with the «Vil prøve» list from the API. +- [x] «Min side» with the top 4, the lists and the reviews, and a page for each. - [x] User accounts in the backend. - [x] Database migrations. - [x] Larger dataset on the VM. diff --git a/backend/src/lists/wine-lists.ts b/backend/src/lists/wine-lists.ts index c86d243..99a7776 100644 --- a/backend/src/lists/wine-lists.ts +++ b/backend/src/lists/wine-lists.ts @@ -1,6 +1,7 @@ // The wine lists and their rules, and the SQL that changes and reads them. // The database checks what it can (see the user_wine migration); the rules that span two -// lists are here, and run in one transaction. +// lists are here, and run in one transaction. The frontend repeats them in +// frontend/src/lib/wineLists.ts, so a button can change before the answer: change both together. import type { PoolClient } from 'pg'; import { decodeIdCursor } from '../connection'; import { pool } from '../db'; diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts index df139e6..a3abfb3 100644 --- a/backend/src/resolvers.ts +++ b/backend/src/resolvers.ts @@ -206,21 +206,30 @@ export const resolvers = { // User comes from auth/resolvers.ts. Fields that belong to other features are added here. User: { - // Newest written first. The order is by id, which an edit does not change, so editing a - // review while someone pages through the list neither skips nor repeats one. - async reviews(user: { id: string }, args: { first?: number | null; after?: string | null }) { + // By when the review was given, newest or oldest first. The order is by id, which an edit + // does not change, so editing a review while someone pages through the list neither skips + // nor repeats one. The cursor is the id of the last review on the page, in both orders. + async reviews( + user: { id: string }, + args: { first?: number | null; after?: string | null; order?: 'NEWEST' | 'OLDEST' | null }, + ) { const userId = Number(user.id); const first = limitReviews(args.first, 10); - const before = decodeIdCursor(args.after); - // The index review_user_id covers both queries. - const [list, count] = await Promise.all([ - pool.query( - `SELECT * FROM review + const afterId = decodeIdCursor(args.after); + // Fixed SQL for each order, never text from the request. The index review_user_id + // (user_id, id DESC) covers both, read forwards or backwards. + const page = + args.order === 'OLDEST' + ? `SELECT * FROM review + WHERE user_id = $1 AND ($2::integer IS NULL OR id > $2) + ORDER BY id ASC + LIMIT $3` + : `SELECT * FROM review WHERE user_id = $1 AND ($2::integer IS NULL OR id < $2) ORDER BY id DESC - LIMIT $3`, - [userId, before, first + 1], - ), + LIMIT $3`; + const [list, count] = await Promise.all([ + pool.query(page, [userId, afterId, first + 1]), pool.query<{ total: number }>('SELECT count(*)::int AS total FROM review WHERE user_id = $1', [ userId, ]), diff --git a/backend/src/review-api.db.test.ts b/backend/src/review-api.db.test.ts index 09be536..54b9e58 100644 --- a/backend/src/review-api.db.test.ts +++ b/backend/src/review-api.db.test.ts @@ -21,8 +21,8 @@ const url = process.env.TEST_DATABASE_URL; const SAVE = `mutation Save($input: ReviewInput!) { saveReview(input: $input) { id rating comment author } }`; const DELETE = `mutation Delete($wineId: ID!) { deleteReview(wineId: $wineId) }`; const MINE = `query Mine($wineId: ID!) { myReview(wineId: $wineId) { id rating comment author } }`; -const MY_REVIEWS = `query MyReviews($first: Int, $after: String) { - me { reviews(first: $first, after: $after) { +const MY_REVIEWS = `query MyReviews($first: Int, $after: String, $order: ReviewOrder) { + me { reviews(first: $first, after: $after, order: $order) { totalCount edges { node { rating wine { id } } } pageInfo { hasNextPage endCursor } @@ -215,6 +215,42 @@ describe.skipIf(!url)('reviews API (PostgreSQL)', () => { expect(second.edges.map((edge) => edge.node)).toEqual([{ rating: 5, wine: { id: wineId } }]); }); + it('lists the oldest first with order: OLDEST, one page at a time, without skipping', async () => { + const eva = await createBrowser('eva'); + await eva.request(SAVE, save(4)); + await eva.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); + + const first = pageOf(await eva.request(MY_REVIEWS, { first: 1, order: 'OLDEST' })); + expect(first.totalCount).toBe(2); + expect(first.edges.map((edge) => edge.node)).toEqual([{ rating: 4, wine: { id: wineId } }]); + expect(first.pageInfo.hasNextPage).toBe(true); + + // Editing the review already shown neither moves it nor repeats it on the next page. + await eva.request(SAVE, save(5)); + + const second = pageOf( + await eva.request(MY_REVIEWS, { first: 1, after: first.pageInfo.endCursor, order: 'OLDEST' }), + ); + expect(second.edges.map((edge) => edge.node)).toEqual([{ rating: 2, wine: { id: otherWineId } }]); + expect(second.pageInfo.hasNextPage).toBe(false); + }); + + it('lists the newest first when the order is NEWEST or left out', async () => { + const ole = await createBrowser('ole'); + await ole.request(SAVE, save(4)); + await ole.request(SAVE, { input: { wineId: otherWineId, rating: 2 } }); + + for (const order of [undefined, 'NEWEST']) { + const page = pageOf(await ole.request(MY_REVIEWS, { order })); + expect(page.edges.map((edge) => edge.node.wine.id)).toEqual([otherWineId, wineId]); + } + }); + + it('rejects an order that does not exist', async () => { + const per = await createBrowser('per'); + expect(codeOf(await per.request(MY_REVIEWS, { order: 'BEST' }))).toBe('BAD_USER_INPUT'); + }); + it('rejects a cursor that was not made by the API', async () => { const ina = await createBrowser('ina'); expect(codeOf(await ina.request(MY_REVIEWS, { after: 'not-a-cursor' }))).toBe('BAD_USER_INPUT'); diff --git a/backend/src/schema.ts b/backend/src/schema.ts index cedace9..7d0048b 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -116,10 +116,19 @@ export const typeDefs = `#graphql pageInfo: PageInfo! } + "The order of a user's reviews: by when each review was first given (an edit does not move it)." + enum ReviewOrder { + NEWEST + OLDEST + } + # User is defined in auth/schema.ts. Reviews are public, so this works for any user. extend type User { - "The user's reviews, newest first. Use pageInfo.endCursor as 'after' to load more." - reviews(first: Int = 10, after: String): ReviewConnection! + """ + The user's reviews, by when they were given: newest first, or oldest first. Use + pageInfo.endCursor as 'after' to load more, with the same order. + """ + reviews(first: Int = 10, after: String, order: ReviewOrder = NEWEST): ReviewConnection! } "The author is always the logged-in user, so it is not part of the input." @@ -164,4 +173,4 @@ export const typeDefs = `#graphql """ deleteReview(wineId: ID!): Boolean! } -`; \ No newline at end of file +`; diff --git a/docs/api.md b/docs/api.md index 902791d..75eaca8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -102,15 +102,18 @@ mutation DeleteReview($wineId: ID!) { # requires login, deletes on } ``` -A user's reviews are a field on `User`, newest first, with the same pages as the wine search. -Reviews are public, so the field is meant for other users' profiles as well: +A user's reviews are a field on `User`. Reviews are public, so the field is meant for other users' +profiles as well. `order` is `NEWEST` (the default) or `OLDEST`, by when each review was *given*: +an edit does not move a review, so a review edited while someone pages through the list is neither +skipped nor shown twice. The cursor is the id of the last review on the page, in both orders; pass +the same `order` with `after`. ```graphql -query MyReviews($after: String) { +query MyReviews($after: String, $order: ReviewOrder!) { me { - reviews(first: 10, after: $after) { + reviews(first: 10, after: $after, order: $order) { totalCount - edges { node { rating comment updatedAt wine { id name } } } + edges { node { rating comment createdAt updatedAt wine { id name } } } pageInfo { hasNextPage endCursor } } } @@ -120,7 +123,7 @@ query MyReviews($after: String) { | Error code | When | |---|---| | `UNAUTHENTICATED` | `saveReview` or `deleteReview` without a valid session | -| `BAD_USER_INPUT` | A rating that is not 0.5–5 in half stars, a too long comment, an unknown wine, or an invalid cursor | +| `BAD_USER_INPUT` | A rating that is not 0.5–5 in half stars, a too long comment, an unknown wine, an invalid cursor, or an unknown `order` | `first` is limited to 50. `studentRating`, `reviews`, `Review.author` and `Review.wine` are loaded in batches with DataLoader, so a page of wines or reviews runs one query per field instead of one per row. @@ -210,7 +213,7 @@ In the frontend, put the page under `` in `App.tsx`, and read the u | `auth/auth-service.test.ts` | Register, login, logout and session expiry with an in-memory store | | `auth/auth-api.test.ts` | Real GraphQL requests through Apollo Server, with a fake browser that keeps the cookie: two browsers, logout, forged cookies, error codes, and that no field exposes the password hash | | `auth/user-store.db.test.ts` | The SQL against PostgreSQL. Skipped unless `TEST_DATABASE_URL` is set | -| `review-api.db.test.ts` | Reviews through Apollo Server against PostgreSQL, with one fake browser per user: login required, one review per user and wine, users cannot see or delete each other's reviews, the average follows at once, old anonymous reviews, and `User.reviews` with pages that neither skip nor repeat a review edited meanwhile. Skipped unless `TEST_DATABASE_URL` is set | +| `review-api.db.test.ts` | Reviews through Apollo Server against PostgreSQL, with one fake browser per user: login required, one review per user and wine, users cannot see or delete each other's reviews, the average follows at once, old anonymous reviews, and `User.reviews` newest or oldest first, with pages that neither skip nor repeat a review edited meanwhile. Skipped unless `TEST_DATABASE_URL` is set | ## Wine lists @@ -288,17 +291,42 @@ The code is in `frontend/src/features/lists/`. | Part | What it does | |---|---| -| `myLists` in the wine queries | The search, the landing page, the wine page and «Mine anmeldelser» ask for `myLists` with each wine, so a page needs no extra request for the buttons | -| `useWineList(wineId, list)` | Returns `{ isSaved, toggle, error }`. Reads `myLists` from the cache with `useFragment`, so every button for the same wine agrees. The button changes at once (`optimisticResponse`, with the same rules as the API in `lib/wineLists.ts`), and goes back with a Norwegian message if the request fails. A visitor is sent to `/konto` and back | +| `lib/wineLists.ts` | The list rules, so a button can change before the API answers. The same rules as `backend/src/lists/wine-lists.ts`: change both together. Both are tested | +| `myLists` in the wine queries | The search, the landing page, the wine page, «Min side» and the list pages ask for `myLists` with each wine, so a page needs no extra request for the buttons | +| `useWineList(wineId, list)` | Returns `{ isSaved, toggle, error }`. One change at a time per wine and list, also across buttons (a heart on a card and «Favoritt» on the wine page), so two requests never arrive in the wrong order. Reads `myLists` from the cache with `useFragment`, so every button for the same wine agrees. The button changes at once (`optimisticResponse`, with the same rules as the API in `lib/wineLists.ts`), and goes back with a Norwegian message if the request fails. A visitor is sent to `/konto` and back | | `WineListButtons` | «Favoritt», «Vil prøve» and «Har prøvd» on the wine page: toggle buttons (`aria-pressed`) with visible text, in a named group | | `WineCardListButtons` | The heart and the bookmark on each wine card. Icons only, with the wine's name in the accessible name | -| `useMyWineList(list)` | One of the user's lists, 24 wines per page, for «Mine anmeldelser» (behind login) and later the profile | +| `useMyWineList(list)` | One of the user's lists, 24 wines per page, for the list pages and the top 4 editor. It shows what the cache has at once, and always asks for a whole page too (`cache-and-network`), since «Min side» keeps only the first four of each list in the same place | | `updateListPages` | Keeps the cached list pages in step with a change: a wine that left a list is taken out at once, and a list the wine joined is fetched again the next time it is shown, with the new wine first | -| `useLegacyWishlistImport` | Moves a «Vil prøve» list stored in the browser before login (`kk:wishlist`) to the user once, oldest first. A wine that no longer exists is skipped. The old list is only removed when every wine has been handled | +| `useLegacyWishlistImport` | Moves a «Vil prøve» list stored in the browser before login (`kk:wishlist`) to the user once, oldest first. A wine that no longer exists is skipped. The old list is only removed when every wine has been handled. The browser cannot know whose list it was, so on a shared computer it goes to the first user who logs in. It only covers lists from before login came, so we accept that | Frontend tests: `lib/wineLists.test.ts`, `features/lists/**/*.test.ts(x)`, `components/ui/WineCard.test.tsx`, -`features/my/MyPage.test.tsx`, and `e2e/lists.spec.ts`, which runs the whole flow against a small fake -API that remembers the lists. +`features/my/**/*.test.ts(x)`, and `e2e/lists.spec.ts` and `e2e/profile.spec.ts`, which run the whole +flow against the fake API in `e2e/support/fakeApi.ts`. It remembers the lists and the top 4. + +### «Min side» + +The code is in `frontend/src/features/my/`. Every page is behind `RequireAuth`. + +| Address | What it shows | +|---|---| +| `/mine` | «Min side»: the username and «Medlem siden …», the top 4, the four newest wines on each list with «Se alle», and the four newest reviews. All in one request (`MyProfile`) | +| `/mine/favoritter`, `/mine/vil-prove`, `/mine/har-provd` | One whole list, newest first, 24 at a time with «Last inn flere». An unknown list shows «Fant ikke listen» | +| `/mine/dommer` | All the user's reviews, «Nyeste først» or «Eldste først» (`?sortering=eldste` in the URL), 10 at a time | + +| Part | What it does | +|---|---| +| `useMyProfile` | The `MyProfile` query. The lists in it are stored by name (`User.wines` with `keyArgs: ['list']`), so they are the same ones the list pages show, and a button on a card updates both. While a list is fetched again, the page keeps what it had (`previousData`) | +| `TopFavourites` | The top 4 in its own frame: always four numbered places, «Ledig plass» for a free one, and «Endre topp 4» when the user has favourites | +| `TopFavouritesEditor` | Choosing the top 4 with buttons only (no drag and drop): «Flytt opp», «Flytt ned», «Ta ut» and «Legg til», named with the wine («Flytt opp Origem Merlot»). Each change is read out in a live region, and focus stays on the button or moves to the nearest one when it is gone. Nothing is saved before «Lagre topp 4». The answer from `setTopFavourites` is the user, so «Min side» updates from it without a new request | +| `topFavouritesDraft.ts` | The steps of the editor as pure functions, with at most four wines, the same limit as the API | +| `ReviewItem` | One review: the wine, the stars, «Gitt …» and «· endret …» when it was saved again later | +| `useRemovalMessage` | When a wine taken off a list disappears from the page, says so in a live region and moves focus to the list's heading | + +Known limits, on purpose: when a wine is taken off a list on «Min side», the preview shows one wine +fewer until the page is loaded again (fetching the list again would also reset «Last inn flere» on +the list pages). «Min side» shows changes made in another tab or device after a reload. Changes in +«Endre topp 4» are lost when the user leaves the page without saving. ## Demo user diff --git a/docs/manual-testing.md b/docs/manual-testing.md index 6e1b1a4..e91200d 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -98,8 +98,8 @@ Things that should fail: | Logged out: press the heart on a wine card | You are sent to `/konto`. After logging in, you come back to the same page | | Logged in: press the heart and the bookmark on a card | Both fill in at once. The same wine elsewhere on the page, and on the wine page, shows the same | | On the wine page: «Vil prøve», then «Har prøvd» | «Vil prøve» turns off at once | -| «Mine anmeldelser» | The wines with a bookmark, newest first. Logged out, the page sends you to `/konto` | -| On «Mine anmeldelser»: press the bookmark on a wine | The card goes at once, «Fjernet fra listen …» is read, and focus moves to «Vil prøve» | +| `/mine/vil-prove` | The wines with a bookmark, newest first. Logged out, the page sends you to `/konto` | +| On `/mine/vil-prove`: press the bookmark on a wine | The card goes at once, «Fjernet fra listen …» is read, and focus moves to the heading «Vil prøve» | | The same user in a private window | The same lists: they are stored on the user, not in the browser | | Stop the backend and press a heart | The heart goes back, with «Vi fikk ikke lagret endringen.» and the reason | | Only the keyboard: Tab to the buttons, Space or Enter | Everything can be reached and changed, and focus is always visible | @@ -110,7 +110,7 @@ Before login, «Vil prøve» was stored in the browser. It moves to the first us 1. Logged out, in the DevTools console: `localStorage.setItem('kk:wishlist', JSON.stringify(['ID1', 'ID2']))` with two wine ids from your database, and one that does not exist (`'999999999'`). -2. Log in and open «Mine anmeldelser». The two wines are there, `ID2` at the top. +2. Log in and open `/mine/vil-prove`. The two wines are there, `ID2` at the top. 3. `localStorage.getItem('kk:wishlist')` in the console gives `null`: the old list is gone and is not moved again. ## 7. Wine lists and the top 4 through the API @@ -144,7 +144,38 @@ echo "VIN=$VIN" | Log in as `demo` / `kork-og-krone` at `/konto` | Logged in | | `q "{ me { topFavourites { name } wines(list: FAVOURITE) { totalCount } reviews { totalCount } } }"` as `demo` | Four wines in the top 4, six favourites and five reviews | -## 9. Accessibility +## 9. «Min side» + +Log in as `demo` (see section 8), which has favourites, a top 4, both other lists and reviews. + +| Step | Expected | +|---|---| +| «Min side» in the menu | The username and «Medlem siden …», the top 4 in its frame with four numbered places, the four newest wines on each list with «Se alle …», and «Mine dommer» | +| Logged out: open `/mine`, `/mine/favoritter` or `/mine/dommer` | You are sent to `/konto`, and come back to the same page after logging in | +| A new user with nothing saved | Every part explains how to fill it, with a link to the search. The top 4 shows four «Ledig plass» | +| «Se alle … favoritter» | The whole list, «Tilbake til Min side» at the top. With more than 24, «Last inn flere», and focus on the first new wine | +| A wine in a list on «Min side», then its back link | «Tilbake til Min side», or «Tilbake til listen» from a list page | +| Take the heart off a wine in the top 4, in «Favoritter» | It leaves «Favoritter» and the top 4 at once. Focus moves to the heading, and «Fjernet fra listen …» is read | +| «Endre topp 4» | Focus on the heading «Endre topp 4». The top 4 in order, with «Flytt opp», «Flytt ned» and «Ta ut», and the other favourites with «Legg til» | +| Move a wine down, take one out, add another, «Lagre topp 4» | The new order in the frame, «Topp 4 er lagret.» is read, and focus is on «Endre topp 4». The same after a reload and in a private window | +| Four wines chosen: «Legg til» on a fifth | Nothing happens, and the button is described by «Topp 4 er full …» | +| Change something, then «Avbryt» | The top 4 as before | +| `/mine/dommer`: «Eldste først», then reload | The oldest first, `?sortering=eldste` in the URL, and the same order after the reload | +| Edit an old review on its wine page, back to `/mine/dommer` | It keeps its place, with «Gitt … · endret …» | +| `/mine/noe-annet` | «Fant ikke listen», with a link to «Min side» | + +With only the keyboard (Tab, Shift+Tab, Enter, Space) and with a screen reader (NVDA: H for the +next heading; VoiceOver: VO+Cmd+H): + +| Step | Expected | +|---|---| +| Move through «Min side» by headings | «Min side» (h1), then «Topp 4», «Favoritter», «Vil prøve», «Har prøvd» and «Mine dommer» (h2), and each wine or review (h3) | +| The whole of «Endre topp 4» with only the keyboard | Every button can be reached and pressed, focus is always visible and never jumps to the top of the page | +| «Flytt opp» on the wine in place 1 | Read as dimmed or unavailable, and it can still have focus | +| Each change in «Endre topp 4» | Read out, for example «Origem Merlot er flyttet til plass 2.» | +| axe DevTools on «Min side», with and without «Endre topp 4» open, and on `/mine/dommer` | No violations | + +## 10. Accessibility | Step | Expected | |---|---| diff --git a/docs/screen-reader.md b/docs/screen-reader.md index ec73deb..6153ec2 100644 --- a/docs/screen-reader.md +++ b/docs/screen-reader.md @@ -23,7 +23,7 @@ Found by stepping through the flows. Each one has a test that fails without the | Login | The button was disabled while logging in, so focus was lost when the login failed. | `aria-disabled` instead of `disabled`, so focus stays on the button. Double clicks are still ignored. | | Login: «Lag bruker» / «Logg inn» | The form changed, but focus stayed on the switch button, so nothing told the user which form they were in. | Focus moves to the new h1, and the page title changes with it. | | Lag bruker: the password field | «Minst 8 tegn.» was shown under the field but not read with it. Only the username had its hint linked. | `aria-describedby` on the password field too. | -| Mine anmeldelser: removing a wine from «Vil prøve» | The card disappeared with the button, focus was lost, and nothing was announced. | The live region says «Fjernet fra listen. 1 vin igjen.», and focus moves to the list heading. | +| The «Vil prøve» list: removing a wine | The card disappeared with the button, focus was lost, and nothing was announced. | The live region says «Fjernet fra listen. 1 vin igjen.», and focus moves to the list heading. | | All pages, in development only | React StrictMode runs effects twice, so focus jumped to the h1 on the very first load. Production did not do this, so testing on the dev server gave a different result. | The layout compares with the previous path instead of counting renders. | Checked and fine: landmarks, one h1 per page, focus on the h1 after navigation, page titles, names on all buttons and form fields, «Vil prøve» as a toggle button (`aria-pressed`), the star rating as ten radio buttons, star ratings as text, the filter dialog (focus inside, Escape closes, focus back to the button), «Last inn flere» (focus on the first new wine), and the live regions for search results, loading and errors. @@ -69,7 +69,7 @@ For each step, write down what VoiceOver says if it differs from the expected re | 8 | Open a wine. Find «Gi din dom» and use the arrow keys in the stars. | «0,5 av 5 stjerner, radio button, 1 of 10», and so on up to 5. | | 9 | Choose 4 stars, write a comment, press «Lagre dommen». | «Dommen er lagret.» Focus on «Oppdater dommen». | | 10 | Press «Slett dommen». | «Dommen er slettet.» Focus on «Lagre dommen». | -| 11 | Press «Vil prøve» on the wine page, then go to «Mine anmeldelser» and press it again on the card. | «Fjernet fra listen. Listen er tom.» Focus on «Vil prøve, heading level 2». | +| 11 | Press «Vil prøve» on the wine page, then go to `/mine/vil-prove` and press it again on the card. | «Fjernet fra listen. Listen er tom.» Focus on «Vil prøve, heading level 1». | | 12 | Go to «Logg inn», log in with a wrong password. | «Feil brukernavn eller passord.» Focus still on «Logg inn». | | 13 | Press «Lag bruker». | «Lag bruker, heading level 1». The field hints are read with the fields. | | 14 | On a phone-sized window: open «Filtrer», choose a filter, close with «Vis … viner». | The dialog is announced with its heading, and focus goes back to «Filtrer (1 valgt)». | diff --git a/frontend/.gitignore b/frontend/.gitignore deleted file mode 100644 index a29f5d6..0000000 --- a/frontend/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ - -# Playwright and coverage -test-results/ -playwright-report/ -blob-report/ -coverage/ diff --git a/frontend/e2e/lists.spec.ts b/frontend/e2e/lists.spec.ts index 0acb95f..62f3bc1 100644 --- a/frontend/e2e/lists.spec.ts +++ b/frontend/e2e/lists.spec.ts @@ -1,124 +1,17 @@ -import AxeBuilder from '@axe-core/playwright'; import { expect, test, type Page } from '@playwright/test'; -import { stubGraphQL } from './support/graphql'; +import { expectNoAxeViolations } from './support/axe'; +import { fakeApi, loggedIn } from './support/fakeApi'; /* - * E2E for the wine lists: the buttons on the wine cards and the wine page, «Mine anmeldelser», + * E2E for the wine lists: the buttons on the wine cards and the wine page, the list pages, * login on the way, and the move of an old «Vil prøve» list from the browser. - * Runs against `vite preview` with a small fake API that remembers the lists like the real one. + * Runs against `vite preview` with the fake API in support/fakeApi.ts, which remembers the lists. */ -type ListName = 'FAVOURITE' | 'WANT_TO_TRY' | 'TRIED'; -const ORDER: ListName[] = ['FAVOURITE', 'WANT_TO_TRY', 'TRIED']; - -const KARI = { __typename: 'User', id: '1', username: 'kari', createdAt: '2026-11-19T12:00:00Z' }; - -const wineFields = (id: string) => ({ - __typename: 'Wine', - id, - name: `Rødvin ${id}`, - type: 'Red', - grapes: ['Merlot'], - country: 'Italy', - countryCode: 'IT', - wineryName: 'Testprodusent', - communityRating: 4, - communityRatingCount: 10, -}); - -const details = { - regionName: 'Toscana', - website: null, - elaborate: null, - harmonize: [], - abv: 13, - body: null, - acidity: null, - vintages: [], -}; - -const connection = (nodes: object[]) => ({ - __typename: 'WineConnection', - totalCount: nodes.length, - edges: nodes.map((node, index) => ({ __typename: 'WineEdge', cursor: String(index), node })), - pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null }, -}); - -/** - * A fake API with three wines. It keeps each wine's lists, and when it was added to each list, - * so «Mine anmeldelser» shows the newest first. `loggedIn: false` starts as a visitor, and - * `Login` logs Kari in, as the real API does with the session cookie. - */ -async function fakeApi(page: Page, { loggedIn = true } = {}) { - let me: typeof KARI | null = loggedIn ? KARI : null; - const added = new Map(); // `${wineId}:${list}` → when it was added - let clock = 0; - const ids = ['1', '2', '3']; - - const listsOf = (wineId: string): ListName[] => - me ? ORDER.filter((list) => added.has(`${wineId}:${list}`)) : []; - const wine = (wineId: string) => ({ ...wineFields(wineId), myLists: listsOf(wineId) }); - - await stubGraphQL(page, { - Me: () => ({ data: { me } }), - Login: () => { - me = KARI; - return { data: { login: KARI } }; - }, - SearchWines: () => ({ data: { wines: connection(ids.map(wine)) } }), - Wine: ({ id }: { id: string }) => ({ data: { wine: { ...wine(id), ...details } } }), - WineReviews: ({ id }: { id: string }) => ({ - data: { - wine: { - __typename: 'Wine', - id, - studentRating: { __typename: 'StudentRating', average: null, count: 0 }, - ratingDistribution: [], - reviews: [], - }, - myReview: null, - }, - }), - SetWineInList: ({ - wineId, - list, - inList, - }: { - wineId: string; - list: ListName; - inList: boolean; - }) => { - if (inList) { - if (!added.has(`${wineId}:${list}`)) added.set(`${wineId}:${list}`, (clock += 1)); - if (list === 'TRIED') added.delete(`${wineId}:WANT_TO_TRY`); - } else { - added.delete(`${wineId}:${list}`); - } - return { - data: { setWineInList: { __typename: 'Wine', id: wineId, myLists: listsOf(wineId) } }, - }; - }, - MyWineList: ({ list }: { list: ListName }) => { - const onList = ids - .filter((id) => added.has(`${id}:${list}`)) - .sort((a, b) => (added.get(`${b}:${list}`) ?? 0) - (added.get(`${a}:${list}`) ?? 0)); - return { data: { me: me && { ...me, wines: connection(onList.map(wine)) } } }; - }, - }); -} -/** The header shows the username once the page knows who is logged in. Clicks wait for that. */ -const loggedIn = (page: Page) => expect(page.getByRole('link', { name: 'kari' })).toBeAttached(); const myList = (page: Page) => page.getByRole('list', { name: 'Viner du vil prøve' }); -async function expectNoAxeViolations(page: Page) { - const axe = await new AxeBuilder({ page }) - .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']) - .analyze(); - expect(axe.violations).toEqual([]); -} - test.describe('Listene', () => { - test('bokmerket på et kort legger vinen på «Mine anmeldelser», og tar den av igjen', async ({ + test('bokmerket på et kort legger vinen på «Vil prøve», og tar den av igjen', async ({ page, }) => { await fakeApi(page); @@ -132,7 +25,7 @@ test.describe('Listene', () => { await expect(bookmark).toHaveAttribute('aria-pressed', 'true'); // A new page load: the list comes from the API, not from this browser. - await page.goto('./mine'); + await page.goto('./mine/vil-prove'); await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 2']); await expectNoAxeViolations(page); @@ -141,7 +34,7 @@ test.describe('Listene', () => { await page.keyboard.press('Enter'); await expect(page.getByText('Fjernet fra listen. Listen er tom.')).toBeAttached(); - await expect(page.getByRole('heading', { level: 2, name: 'Vil prøve' })).toBeFocused(); + await expect(page.getByRole('heading', { level: 1, name: 'Vil prøve' })).toBeFocused(); await expect(page.getByText(/Du har ikke lagret noen viner ennå/)).toBeVisible(); }); @@ -159,7 +52,7 @@ test.describe('Listene', () => { await expect(tried).toHaveAttribute('aria-pressed', 'true'); await expect(wantToTry).toHaveAttribute('aria-pressed', 'false'); - await page.goto('./mine'); + await page.goto('./mine/vil-prove'); await expect(page.getByText(/Du har ikke lagret noen viner ennå/)).toBeVisible(); }); @@ -188,7 +81,7 @@ test.describe('Listene', () => { localStorage.setItem('kk:wishlist', JSON.stringify(['2', '1'])); }); await fakeApi(page); - await page.goto('./mine'); + await page.goto('./mine/vil-prove'); await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 1', 'Rødvin 2']); await expect.poll(() => page.evaluate(() => localStorage.getItem('kk:wishlist'))).toBeNull(); @@ -198,10 +91,14 @@ test.describe('Listene', () => { await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 1', 'Rødvin 2']); }); - test('har ingen axe-brudd på en tom «Mine anmeldelser»', async ({ page }) => { + test('har ingen axe-brudd på en tom «Min side» og en tom liste', async ({ page }) => { await fakeApi(page); await page.goto('./mine'); await expect(page.getByText(/Du har ikke lagret noen viner ennå/)).toBeVisible(); await expectNoAxeViolations(page); + + await page.goto('./mine/har-provd'); + await expect(page.getByText(/Du har ikke merket noen viner som prøvd ennå/)).toBeVisible(); + await expectNoAxeViolations(page); }); }); diff --git a/frontend/e2e/profile.spec.ts b/frontend/e2e/profile.spec.ts new file mode 100644 index 0000000..fda0ab1 --- /dev/null +++ b/frontend/e2e/profile.spec.ts @@ -0,0 +1,102 @@ +import { expect, test, type Page } from '@playwright/test'; +import { expectNoAxeViolations } from './support/axe'; +import { fakeApi, loggedIn } from './support/fakeApi'; + +/* + * E2E for «Min side», the whole way a user goes: log in, add favourites, choose the top 4 with + * the keyboard, see the profile, and log out. Runs against `vite preview` with the fake API in + * support/fakeApi.ts, which remembers the lists and the top 4 between page loads. + */ + +const topPlaces = (page: Page) => + page.getByRole('list', { name: 'Topp 4 favoritter' }).getByRole('link'); + +async function logIn(page: Page) { + await page.getByRole('textbox', { name: 'Brukernavn' }).fill('kari'); + await page.getByLabel('Passord').fill('langt-nok-passord'); + await page.getByRole('main').getByRole('button', { name: 'Logg inn' }).click(); +} + +/** Focuses a button and presses Enter, as a keyboard user does. */ +async function press(page: Page, name: string) { + await page.getByRole('button', { name, exact: true }).focus(); + await page.keyboard.press('Enter'); +} + +test.describe('Min side', () => { + test('logg inn, legg til favoritter, velg topp 4, se profilen og logg ut', async ({ page }) => { + const api = await fakeApi(page, { loggedIn: false }); + + // A visitor is sent to log in, and comes back to «Min side» afterwards. + await page.goto('./mine'); + await expect(page).toHaveURL(/\/konto$/); + await logIn(page); + await expect(page.getByRole('heading', { level: 1, name: 'Min side' })).toBeVisible(); + await expect(page.getByText('Ledig plass')).toHaveCount(4); + + // Two favourites from the search, with the keyboard. + await page.goto('./sok'); + await loggedIn(page); + await press(page, 'Favoritt Rødvin 1'); + await press(page, 'Favoritt Rødvin 2'); + await expect(page.getByRole('button', { name: 'Favoritt Rødvin 2' })).toHaveAttribute( + 'aria-pressed', + 'true', + ); + + // Choose the top 4: both favourites, Rødvin 2 first. + await page.goto('./mine'); + await press(page, 'Endre topp 4'); + await expect(page.getByRole('heading', { name: 'Endre topp 4' })).toBeFocused(); + await press(page, 'Legg til Rødvin 1'); + await press(page, 'Legg til Rødvin 2'); + await press(page, 'Flytt opp Rødvin 2'); + await expect(page.getByRole('button', { name: 'Flytt opp Rødvin 2' })).toBeFocused(); + await expectNoAxeViolations(page); + await press(page, 'Lagre topp 4'); + + await expect(topPlaces(page)).toHaveText(['Rødvin 2', 'Rødvin 1']); + await expect(page.getByRole('button', { name: 'Endre topp 4' })).toBeFocused(); + await expect(page.getByText('Topp 4 er lagret.')).toBeAttached(); + expect(api.top()).toEqual(['2', '1']); + + // The profile comes from the server: the same after a reload. + await page.reload(); + await expect(topPlaces(page)).toHaveText(['Rødvin 2', 'Rødvin 1']); + await expect(page.getByText('Ledig plass')).toHaveCount(2); + await expect( + page.getByRole('region', { name: 'Favoritter' }).getByRole('link', { name: /Se alle/ }), + ).toHaveText('Se alle 2 favoritter'); + await expectNoAxeViolations(page); + + // Log out: «Min side» asks for login again. + await page.goto('./konto'); + await page.getByRole('button', { name: 'Logg ut' }).click(); + await expect(page.getByRole('main').getByRole('button', { name: 'Logg inn' })).toBeVisible(); + await page.goto('./mine'); + await expect(page).toHaveURL(/\/konto$/); + }); + + test('en vin som ikke lenger er favoritt, forsvinner fra topp 4', async ({ page }) => { + await fakeApi(page); + await page.goto('./sok'); + await loggedIn(page); + await press(page, 'Favoritt Rødvin 1'); + await press(page, 'Favoritt Rødvin 3'); + + await page.goto('./mine'); + await press(page, 'Endre topp 4'); + await press(page, 'Legg til Rødvin 1'); + await press(page, 'Legg til Rødvin 3'); + await press(page, 'Lagre topp 4'); + await expect(topPlaces(page)).toHaveText(['Rødvin 1', 'Rødvin 3']); + + // The heart in the favourites on the same page. + await page + .getByRole('region', { name: 'Favoritter' }) + .getByRole('button', { name: 'Favoritt Rødvin 1' }) + .click(); + + await expect(topPlaces(page)).toHaveText(['Rødvin 3']); + }); +}); diff --git a/frontend/e2e/support/axe.ts b/frontend/e2e/support/axe.ts new file mode 100644 index 0000000..038d09d --- /dev/null +++ b/frontend/e2e/support/axe.ts @@ -0,0 +1,10 @@ +import AxeBuilder from '@axe-core/playwright'; +import { expect, type Page } from '@playwright/test'; + +/** No violations of WCAG 2.1 A and AA on the page as it is now. */ +export async function expectNoAxeViolations(page: Page) { + const axe = await new AxeBuilder({ page }) + .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']) + .analyze(); + expect(axe.violations).toEqual([]); +} diff --git a/frontend/e2e/support/fakeApi.ts b/frontend/e2e/support/fakeApi.ts new file mode 100644 index 0000000..4e755fc --- /dev/null +++ b/frontend/e2e/support/fakeApi.ts @@ -0,0 +1,167 @@ +import { expect, type Page } from '@playwright/test'; +import { stubGraphQL } from './graphql'; + +/* + * A small fake API for the e2e tests of the lists and «Min side». It remembers the user's lists, + * the top 4 and whether anyone is logged in between requests, like the real API, so a test can + * reload the page and see that the data comes from the server and not from the browser. + */ +export type ListName = 'FAVOURITE' | 'WANT_TO_TRY' | 'TRIED'; +const ORDER: ListName[] = ['FAVOURITE', 'WANT_TO_TRY', 'TRIED']; + +export const KARI = { + __typename: 'User', + id: '1', + username: 'kari', + createdAt: '2026-11-19T12:00:00Z', +}; + +const wineFields = (id: string) => ({ + __typename: 'Wine', + id, + name: `Rødvin ${id}`, + type: 'Red', + grapes: ['Merlot'], + country: 'Italy', + countryCode: 'IT', + wineryName: 'Testprodusent', + communityRating: 4, + communityRatingCount: 10, +}); + +const details = { + regionName: 'Toscana', + website: null, + elaborate: null, + harmonize: [], + abv: 13, + body: null, + acidity: null, + vintages: [], +}; + +const connection = (nodes: object[]) => ({ + __typename: 'WineConnection', + totalCount: nodes.length, + edges: nodes.map((node, index) => ({ __typename: 'WineEdge', cursor: String(index), node })), + pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null }, +}); + +const emptyReviews = { + __typename: 'ReviewConnection', + totalCount: 0, + edges: [], + pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null }, +}; + +/** The answer the real API gives to a top 4 that breaks its rules. */ +const badInput = (message: string) => ({ + errors: [{ message, extensions: { code: 'BAD_USER_INPUT' } }], + data: null, +}); + +/** + * Three wines. Each wine's lists are kept with when it was added to each list, so the lists show + * the newest first. `loggedIn: false` starts as a visitor: `Login` logs Kari in and `Logout` out, + * as the real API does with the session cookie. Returns the top 4 as the server has it. + */ +export async function fakeApi(page: Page, { loggedIn = true } = {}) { + let me: typeof KARI | null = loggedIn ? KARI : null; + const added = new Map(); // `${wineId}:${list}` → when it was added + let clock = 0; + let top: string[] = []; + const ids = ['1', '2', '3']; + + const listsOf = (wineId: string): ListName[] => + me ? ORDER.filter((list) => added.has(`${wineId}:${list}`)) : []; + const wine = (wineId: string) => ({ ...wineFields(wineId), myLists: listsOf(wineId) }); + const newestOn = (list: ListName) => + ids + .filter((id) => added.has(`${id}:${list}`)) + .sort((a, b) => (added.get(`${b}:${list}`) ?? 0) - (added.get(`${a}:${list}`) ?? 0)); + + await stubGraphQL(page, { + Me: () => ({ data: { me } }), + Login: () => { + me = KARI; + return { data: { login: KARI } }; + }, + Logout: () => { + me = null; + return { data: { logout: true } }; + }, + SetTopFavourites: ({ wineIds }: { wineIds: string[] }) => { + if (wineIds.length > 4) return badInput('The top list can hold at most 4 wines.'); + if (wineIds.some((id) => !added.has(`${id}:FAVOURITE`))) { + return badInput('Only favourites can be in the top list.'); + } + top = [...wineIds]; + return { + data: { setTopFavourites: { ...KARI, topFavourites: top.map(wine) } }, + }; + }, + MyReviews: () => ({ data: { me: me && { ...me, reviews: emptyReviews } } }), + SearchWines: () => ({ data: { wines: connection(ids.map(wine)) } }), + Wine: ({ id }: { id: string }) => ({ data: { wine: { ...wine(id), ...details } } }), + WineReviews: ({ id }: { id: string }) => ({ + data: { + wine: { + __typename: 'Wine', + id, + studentRating: { __typename: 'StudentRating', average: null, count: 0 }, + ratingDistribution: [], + reviews: [], + }, + myReview: null, + }, + }), + SetWineInList: ({ + wineId, + list, + inList, + }: { + wineId: string; + list: ListName; + inList: boolean; + }) => { + if (inList) { + if (!added.has(`${wineId}:${list}`)) added.set(`${wineId}:${list}`, (clock += 1)); + if (list === 'TRIED') added.delete(`${wineId}:WANT_TO_TRY`); + } else { + added.delete(`${wineId}:${list}`); + // A wine taken off the favourites leaves the top 4, as in the database. + if (list === 'FAVOURITE') top = top.filter((id) => id !== wineId); + } + return { + data: { setWineInList: { __typename: 'Wine', id: wineId, myLists: listsOf(wineId) } }, + }; + }, + MyWineList: ({ list }: { list: ListName }) => ({ + data: { me: me && { ...me, wines: connection(newestOn(list).map(wine)) } }, + }), + MyProfile: ({ preview }: { preview: number }) => { + const page = (list: ListName) => { + const all = newestOn(list); + return { ...connection(all.slice(0, preview).map(wine)), totalCount: all.length }; + }; + return { + data: { + me: me && { + ...me, + topFavourites: top.map(wine), + favourites: page('FAVOURITE'), + wantToTry: page('WANT_TO_TRY'), + tried: page('TRIED'), + reviews: emptyReviews, + }, + }, + }; + }, + }); + + return { top: () => [...top] }; +} + +/** The header shows the username once the page knows who is logged in. Clicks wait for that. */ +export const loggedIn = (page: Page) => + expect(page.getByRole('link', { name: 'kari' })).toBeAttached(); diff --git a/frontend/scripts/voiceover.mjs b/frontend/scripts/voiceover.mjs index 5cadf53..ae68a58 100644 --- a/frontend/scripts/voiceover.mjs +++ b/frontend/scripts/voiceover.mjs @@ -236,14 +236,14 @@ const STEPS = [ }, }, { - title: '«Vil prøve» on the wine page, then remove it on «Mine anmeldelser»', - expected: '«Fjernet fra listen. Listen er tom.» Focus on «Vil prøve, heading level 2».', + title: '«Vil prøve» on the wine page, then remove it on the «Vil prøve» list', + expected: '«Fjernet fra listen. Listen er tom.» Focus on «Vil prøve, heading level 1».', expect: [/fjernet fra listen/i, /vil prøve/i], ms: 10000, async run() { await press(main().getByRole('button', { name: 'Vil prøve', exact: true }), 'Space'); await wait(1500); - await go('mine'); + await go('mine/vil-prove'); await press( main() .getByRole('button', { name: /^Vil prøve/ }) diff --git a/frontend/src/app/App.test.tsx b/frontend/src/app/App.test.tsx index dbb4510..6e8bb37 100644 --- a/frontend/src/app/App.test.tsx +++ b/frontend/src/app/App.test.tsx @@ -36,6 +36,8 @@ describe('AppRoutes', () => { ['/vin/abc', 'Fant ikke vinen'], // Behind login: a visitor is sent to /konto. ['/mine', 'Logg inn'], + ['/mine/favoritter', 'Logg inn'], + ['/mine/dommer', 'Logg inn'], ])('shows the right page for %s', async (route, heading) => { renderRoute(route); expect(await findHeading(heading)).toBeInTheDocument(); diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx index ea5ca11..908a48f 100644 --- a/frontend/src/app/App.tsx +++ b/frontend/src/app/App.tsx @@ -9,6 +9,8 @@ const LandingPage = lazy(() => import('../features/landing/LandingPage')); const SearchPage = lazy(() => import('../features/search/SearchPage')); const WinePage = lazy(() => import('../features/wine/WinePage')); const MyPage = lazy(() => import('../features/my/MyPage')); +const MyListPage = lazy(() => import('../features/my/MyListPage')); +const MyReviewsPage = lazy(() => import('../features/my/MyReviewsPage')); const AccountPage = lazy(() => import('../features/auth/AccountPage')); /** BASE_URL kommer fra `base` i vite.config.ts (f.eks. «/project2/»). */ @@ -21,7 +23,7 @@ export function AppRoutes() { } /> } /> } /> - {/* The lists belong to a user, so the page asks visitors to log in and sends them back. */} + {/* The lists belong to a user, so the pages ask visitors to log in and send them back. */} } /> + {/* A fixed path wins over :list, so «dommer» is never read as a list. */} + + + + } + /> + + + + } + /> } /> } /> diff --git a/frontend/src/components/layout/Header.tsx b/frontend/src/components/layout/Header.tsx index b721b04..d8b0759 100644 --- a/frontend/src/components/layout/Header.tsx +++ b/frontend/src/components/layout/Header.tsx @@ -35,7 +35,7 @@ export function Header({ showSearch = true }: HeaderProps) {
  • - Mine anmeldelser + Min side
  • {/* Nothing until we know who is logged in, so the menu does not flicker. */} diff --git a/frontend/src/components/ui/WineCard.module.css b/frontend/src/components/ui/WineCard.module.css index cf22807..9bbbdc5 100644 --- a/frontend/src/components/ui/WineCard.module.css +++ b/frontend/src/components/ui/WineCard.module.css @@ -111,6 +111,18 @@ color: var(--color-text); } +/* Narrow cards, such as four in a row: the bottle above the text, like a poster. */ +@container (max-width: 17rem) { + .visual, + .body { + grid-column: 1 / -1; + } + + .visual { + width: auto; + } +} + /* Smale kort: stable vurderingene. */ @container (max-width: 20rem) { .ratingRow dt { diff --git a/frontend/src/components/ui/WineList.module.css b/frontend/src/components/ui/WineList.module.css index 5b6e4aa..695cc7b 100644 --- a/frontend/src/components/ui/WineList.module.css +++ b/frontend/src/components/ui/WineList.module.css @@ -11,3 +11,20 @@ .grid > li { display: grid; } + +/* Four wines: one, two or four columns, so the last line is never a single wine. */ +.row { + grid-template-columns: minmax(0, 1fr); +} + +@media (min-width: 36rem) { + .row { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} + +@media (min-width: 64rem) { + .row { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } +} diff --git a/frontend/src/components/ui/WineList.tsx b/frontend/src/components/ui/WineList.tsx index 27b92f2..63480c4 100644 --- a/frontend/src/components/ui/WineList.tsx +++ b/frontend/src/components/ui/WineList.tsx @@ -7,6 +7,14 @@ interface WineListProps { wines: WineSummary[]; headingLevel?: 'h2' | 'h3' | 'h4'; label?: string; + /** A numbered list (an ol element), for lists where the order means something, such as a top 4. */ + ordered?: boolean; + /** + * `grid` (default): as many columns as there is room for, for long lists. + * `row`: four, two or one columns, for a short list of four wines, so it never ends with one + * wine alone on a line. + */ + layout?: 'grid' | 'row'; ref?: Ref; } @@ -17,14 +25,28 @@ interface WineListProps { * (list-style: none) as a list, so «list, 24 items» is never read. The same goes for the * other lists without bullets in the app. Lists inside