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
- Gå til Mine anmeldelser
+ Gå til Min side
{logoutError}
diff --git a/frontend/src/features/lists/api/listCache.ts b/frontend/src/features/lists/api/listCache.ts
index 681f97e..90d7203 100644
--- a/frontend/src/features/lists/api/listCache.ts
+++ b/frontend/src/features/lists/api/listCache.ts
@@ -9,7 +9,7 @@ function listOf(storeFieldName: string): string | null {
/**
* Keeps the user's list pages in the cache in step with a change of one wine's lists, so a page
- * that shows them (such as «Mine anmeldelser») changes at once without a new request.
+ * that shows them (such as «Min side» and the list pages) changes at once without a new request.
*
* - A list the wine left: the wine is taken out, and the count goes down by one. Also from the
* top 4 when it is no longer a favourite.
diff --git a/frontend/src/features/lists/api/myWineListQuery.ts b/frontend/src/features/lists/api/myWineListQuery.ts
index 58b2bab..58b79ff 100644
--- a/frontend/src/features/lists/api/myWineListQuery.ts
+++ b/frontend/src/features/lists/api/myWineListQuery.ts
@@ -1,5 +1,6 @@
import { gql } from '@apollo/client';
import type { ApiWine } from '../../../lib/mapWine';
+import { WINE_CARD_FIELDS } from './wineCardFields';
/**
* One page of one of the logged-in user's lists, newest first. The wine fields are the same as
@@ -14,16 +15,7 @@ export const MY_WINE_LIST_QUERY = gql`
edges {
cursor
node {
- id
- name
- type
- grapes
- country
- countryCode
- wineryName
- communityRating
- communityRatingCount
- myLists
+ ...WineCardFields
}
}
pageInfo {
@@ -33,6 +25,7 @@ export const MY_WINE_LIST_QUERY = gql`
}
}
}
+ ${WINE_CARD_FIELDS}
`;
export interface MyWineListData {
diff --git a/frontend/src/features/lists/api/useMyWineList.ts b/frontend/src/features/lists/api/useMyWineList.ts
index 50ebc7e..96bad02 100644
--- a/frontend/src/features/lists/api/useMyWineList.ts
+++ b/frontend/src/features/lists/api/useMyWineList.ts
@@ -31,7 +31,13 @@ export interface MyWineListResult {
export function useMyWineList(list: WineListName): MyWineListResult {
const { data, error, networkStatus, fetchMore, refetch } = useQuery(
MY_WINE_LIST_QUERY,
- { variables: { list, first: LIST_PAGE_SIZE } },
+ {
+ variables: { list, first: LIST_PAGE_SIZE },
+ // «Min side» keeps the first four wines of each list in the same place in the cache. Show
+ // those at once, but always ask for a whole page too, so a list of six shows all six.
+ fetchPolicy: 'cache-and-network',
+ nextFetchPolicy: 'cache-first',
+ },
);
const isFetchingMore = useRef(false);
const [loadMoreError, setLoadMoreError] = useState();
@@ -60,7 +66,8 @@ export function useMyWineList(list: WineListName): MyWineListResult {
.map(({ node }) => toWineSummary(node))
.filter((wine): wine is WineSummary => wine !== null),
totalCount: connection?.totalCount,
- loading: networkStatus === NetworkStatus.loading,
+ // Only the first load: with wines from the cache on the page, the page is not loading.
+ loading: networkStatus === NetworkStatus.loading && !connection,
loadingMore,
hasNextPage: Boolean(connection?.pageInfo.hasNextPage),
error,
diff --git a/frontend/src/features/lists/api/wineCardFields.ts b/frontend/src/features/lists/api/wineCardFields.ts
new file mode 100644
index 0000000..303a491
--- /dev/null
+++ b/frontend/src/features/lists/api/wineCardFields.ts
@@ -0,0 +1,20 @@
+import { gql } from '@apollo/client';
+
+/**
+ * The fields a wine card shows, with `myLists` for its buttons. Used by every query for the
+ * user's lists, so a wine looks the same on «Min side» and on the list pages.
+ */
+export const WINE_CARD_FIELDS = gql`
+ fragment WineCardFields on Wine {
+ id
+ name
+ type
+ grapes
+ country
+ countryCode
+ wineryName
+ communityRating
+ communityRatingCount
+ myLists
+ }
+`;
diff --git a/frontend/src/features/lists/components/WineCardListButtons.module.css b/frontend/src/features/lists/components/WineCardListButtons.module.css
index 5796c0e..54e81c7 100644
--- a/frontend/src/features/lists/components/WineCardListButtons.module.css
+++ b/frontend/src/features/lists/components/WineCardListButtons.module.css
@@ -5,14 +5,17 @@
top: var(--space-2);
right: var(--space-2);
display: grid;
- gap: var(--space-1);
}
+/*
+ * 44 px wide and 40 px tall: the icons sit closer together than with two 44 px squares, and each
+ * button is still far above the 24 px WCAG 2.5.8 asks for.
+ */
.button {
display: grid;
place-items: center;
width: var(--tap-target);
- height: var(--tap-target);
+ height: 2.5rem;
padding: 0;
border: 0;
border-radius: 50%;
@@ -38,6 +41,14 @@
fill: var(--color-brand);
}
+/* On a narrow card the buttons lie over the bottle's box: keep them inside it, off the edge. */
+@container (max-width: 17rem) {
+ .actions {
+ top: var(--space-5);
+ right: var(--space-5);
+ }
+}
+
/* Below the card's content, across both columns. */
.error {
grid-column: 1 / -1;
diff --git a/frontend/src/features/lists/useWineList.test.tsx b/frontend/src/features/lists/useWineList.test.tsx
index 7be5e38..4661534 100644
--- a/frontend/src/features/lists/useWineList.test.tsx
+++ b/frontend/src/features/lists/useWineList.test.tsx
@@ -1,12 +1,13 @@
import { describe, expect, it } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import { gql } from '@apollo/client';
-import type { MockLink } from '@apollo/client/testing';
-import { MockedProvider } from '@apollo/client/testing/react';
+import { ApolloClient, ApolloLink, gql } from '@apollo/client';
+import { ApolloProvider } from '@apollo/client/react';
+import { MockLink } from '@apollo/client/testing';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router';
import { createApolloCache } from '../../lib/apollo';
import type { WineListName } from '../../lib/wineLists';
+import { HELD_BACK } from '../../test/heldBack';
import { ME_QUERY } from '../auth/api/authQueries';
import { AuthProvider } from '../auth/AuthProvider';
import { useAuth } from '../auth/useAuth';
@@ -68,16 +69,26 @@ const wineWith = (myLists: WineListName[]) => ({
/** The wine is in the cache with `myLists`, as after a search or the wine page. */
function renderButtons(
mocks: MockLink.MockedResponse[],
- { loggedIn = true, lists = [] as WineListName[] } = {},
+ { loggedIn = true, lists = [] as WineListName[], extraTried = false } = {},
) {
const cache = createApolloCache();
cache.writeFragment({
fragment: WINE_LISTS_FRAGMENT,
data: { __typename: 'Wine', id: WINE_ID, myLists: lists },
});
+ // Records each request when it is sent, not when the fake API answers.
+ const sent: { operationName: string; variables: Record }[] = [];
+ const recorder = new ApolloLink((operation, forward) => {
+ sent.push({ operationName: operation.operationName ?? '', variables: operation.variables });
+ return forward(operation);
+ });
+ const client = new ApolloClient({
+ link: ApolloLink.from([recorder, new MockLink([me(loggedIn ? USER : null), ...mocks])]),
+ cache,
+ });
const user = userEvent.setup();
render(
-
+
@@ -88,6 +99,8 @@ function renderButtons(
+ {/* A second button for the same list, like a card and the wine page. */}
+ {extraTried && }
>
}
@@ -96,9 +109,12 @@ function renderButtons(
- ,
+ ,
);
- return { user, cache };
+ /** The variables of each request with this name, in the order they were sent. */
+ const sentAs = (operationName: string) =>
+ sent.filter((request) => request.operationName === operationName).map((r) => r.variables);
+ return { user, cache, sentAs };
}
const button = (list: WineListName) => screen.getByRole('button', { name: list });
@@ -116,7 +132,7 @@ describe('useWineList', () => {
it('changes at once, before the API has answered', async () => {
const { user } = renderButtons(
- [setWineInList('WANT_TO_TRY', true, wineWith(['FAVOURITE', 'WANT_TO_TRY']), 10_000)],
+ [setWineInList('WANT_TO_TRY', true, wineWith(['FAVOURITE', 'WANT_TO_TRY']), HELD_BACK)],
{ lists: ['FAVOURITE'] },
);
await ready();
@@ -126,6 +142,27 @@ describe('useWineList', () => {
expect(button('WANT_TO_TRY')).toHaveAttribute('aria-pressed', 'true');
});
+ it('sends one change at a time, also from two buttons for the same wine and list', async () => {
+ const { user, sentAs } = renderButtons(
+ // The answer is held back, so the first change is still on its way at the second click.
+ [setWineInList('TRIED', true, wineWith(['TRIED']), HELD_BACK)],
+ { extraTried: true },
+ );
+ await ready();
+
+ const [first, second] = screen.getAllByRole('button', { name: 'TRIED' });
+ await user.click(first);
+ await user.click(second);
+
+ // The second click would have taken the wine off again. It was ignored, not sent.
+ await waitFor(() =>
+ expect(sentAs('SetWineInList')).toEqual([{ wineId: WINE_ID, list: 'TRIED', inList: true }]),
+ );
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ expect(first).toHaveAttribute('aria-pressed', 'true');
+ expect(second).toHaveAttribute('aria-pressed', 'true');
+ });
+
it('takes the wine off «Vil prøve» at once when it is marked as tried', async () => {
const { user } = renderButtons(
[setWineInList('TRIED', true, wineWith(['FAVOURITE', 'TRIED']))],
diff --git a/frontend/src/features/lists/useWineList.ts b/frontend/src/features/lists/useWineList.ts
index 665209b..56dbff5 100644
--- a/frontend/src/features/lists/useWineList.ts
+++ b/frontend/src/features/lists/useWineList.ts
@@ -1,5 +1,6 @@
-import { useRef, useState } from 'react';
-import { useFragment, useMutation } from '@apollo/client/react';
+import { useState } from 'react';
+import type { ApolloClient } from '@apollo/client';
+import { useApolloClient, useFragment, useMutation } from '@apollo/client/react';
import { useLocation, useNavigate } from 'react-router';
import { classifyError, ERROR_DETAILS } from '../../lib/errors';
import { listsAfterChange, type WineListName } from '../../lib/wineLists';
@@ -22,6 +23,24 @@ export interface WineListState {
error: string | null;
}
+/**
+ * The changes on their way, as `${wineId}:${list}`, per Apollo client (the app has one; each test
+ * has its own). One change at a time per wine and list: a second click while the first is on its
+ * way is ignored, also when it comes from another button for the same wine (a heart on a card and
+ * «Favoritt» on the wine page). So two requests can never arrive in the wrong order and leave the
+ * list the wrong way round.
+ */
+const pendingByClient = new WeakMap>();
+
+function pendingFor(client: ApolloClient): Set {
+ let pending = pendingByClient.get(client);
+ if (!pending) {
+ pending = new Set();
+ pendingByClient.set(client, pending);
+ }
+ return pending;
+}
+
/**
* Whether a wine is on one of the user's lists, and a function to change it.
*
@@ -32,12 +51,10 @@ export interface WineListState {
*/
export function useWineList(wineId: string, list: WineListName): WineListState {
const { user, loading: checkingLogin } = useAuth();
+ const client = useApolloClient();
const navigate = useNavigate();
const location = useLocation();
const [error, setError] = useState(null);
- // One change at a time: a second click while the first is on its way is ignored, so two
- // requests can never arrive in the wrong order and leave the list the wrong way round.
- const pending = useRef(false);
const [setWineInList] = useMutation(
SET_WINE_IN_LIST_MUTATION,
);
@@ -52,14 +69,17 @@ export function useWineList(wineId: string, list: WineListName): WineListState {
async function change() {
// Until we know who is logged in, a click could go either way.
- if (checkingLogin || pending.current) return;
+ if (checkingLogin) return;
if (!user) {
await navigate('/konto', { state: { from: location.pathname + location.search } });
return;
}
+ const pending = pendingFor(client);
+ const key = `${wineId}:${list}`;
+ if (pending.has(key)) return;
const inList = !isSaved;
- pending.current = true;
+ pending.add(key);
setError(null);
try {
await setWineInList({
@@ -80,7 +100,7 @@ export function useWineList(wineId: string, list: WineListName): WineListState {
} catch (failure) {
setError(`Vi fikk ikke lagret endringen. ${ERROR_DETAILS[classifyError(failure)]}`);
} finally {
- pending.current = false;
+ pending.delete(key);
}
}
diff --git a/frontend/src/features/my/MyListPage.test.tsx b/frontend/src/features/my/MyListPage.test.tsx
new file mode 100644
index 0000000..42035af
--- /dev/null
+++ b/frontend/src/features/my/MyListPage.test.tsx
@@ -0,0 +1,224 @@
+import { describe, expect, it } from 'vitest';
+import { render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { MockLink } from '@apollo/client/testing';
+import { MockedProvider } from '@apollo/client/testing/react';
+import { MemoryRouter, Route, Routes } from 'react-router';
+import { axe } from 'vitest-axe';
+import { createApolloCache } from '../../lib/apollo';
+import { meMock, TEST_USER } from '../../test/authMocks';
+import { AuthReady } from '../../test/AuthReady';
+import { HELD_BACK } from '../../test/heldBack';
+import { AuthProvider } from '../auth/AuthProvider';
+import { SET_WINE_IN_LIST_MUTATION } from '../lists/api/listQueries';
+import { LIST_PAGE_SIZE } from '../lists/api/useMyWineList';
+import { MY_WINE_LIST_QUERY } from '../lists/api/myWineListQuery';
+import MyListPage from './MyListPage';
+
+const apiWine = (id: string, name: string) => ({
+ __typename: 'Wine',
+ id,
+ name,
+ type: 'Red',
+ grapes: ['Merlot'],
+ country: 'Italy',
+ countryCode: 'IT',
+ wineryName: 'Produsent',
+ communityRating: 4.2,
+ communityRatingCount: 12,
+ myLists: ['WANT_TO_TRY'],
+});
+
+type Saved = { id: string; name: string };
+
+/** One page of «Vil prøve», newest first, as the API sends it. */
+function page(
+ saved: Saved[],
+ {
+ totalCount = saved.length,
+ after,
+ next,
+ }: { totalCount?: number; after?: string; next?: string } = {},
+): MockLink.MockedResponse {
+ return {
+ request: {
+ query: MY_WINE_LIST_QUERY,
+ variables: { list: 'WANT_TO_TRY', first: LIST_PAGE_SIZE, ...(after ? { after } : {}) },
+ },
+ result: {
+ data: {
+ me: {
+ __typename: 'User',
+ id: TEST_USER.id,
+ wines: {
+ __typename: 'WineConnection',
+ totalCount,
+ edges: saved.map((wine) => ({
+ __typename: 'WineEdge',
+ cursor: `c${wine.id}`,
+ node: apiWine(wine.id, wine.name),
+ })),
+ pageInfo: {
+ __typename: 'PageInfo',
+ hasNextPage: Boolean(next),
+ endCursor: next ?? null,
+ },
+ },
+ },
+ },
+ },
+ };
+}
+
+function renderPage(
+ mocks: MockLink.MockedResponse[],
+ path = '/mine/vil-prove',
+ cache = createApolloCache(),
+) {
+ const user = userEvent.setup();
+ const result = render(
+
+
+
+
+ } />
+
+
+
+
+ ,
+ );
+ return { user, ...result };
+}
+
+const list = () => screen.findByRole('list', { name: 'Viner du vil prøve' });
+const names = (element: HTMLElement) =>
+ within(element)
+ .getAllByRole('link')
+ .map((link) => link.textContent);
+
+describe('MyListPage', () => {
+ it('explains the empty list and links to the search', async () => {
+ renderPage([page([])]);
+ expect(await screen.findByText(/Du har ikke lagret noen viner ennå/)).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Utforsk viner' })).toHaveAttribute('href', '/sok');
+ expect(document.title).toBe('Vil prøve – Kork & Krone');
+ });
+
+ it('shows the whole list from the API, newest first, under a heading with its name', async () => {
+ renderPage([
+ page([
+ { id: '111427', name: 'Chianti' },
+ { id: '100062', name: 'Origem Merlot' },
+ ]),
+ ]);
+
+ expect(names(await list())).toEqual(['Chianti', 'Origem Merlot']);
+ expect(screen.getByRole('heading', { level: 1, name: 'Vil prøve' })).toBeInTheDocument();
+ expect(screen.getByText('2 viner')).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Tilbake til Min side' })).toHaveAttribute(
+ 'href',
+ '/mine',
+ );
+ });
+
+ it('takes a wine off the list at once when its bookmark is clicked', async () => {
+ const { user } = renderPage([
+ page([{ id: '100062', name: 'Origem Merlot' }]),
+ {
+ request: {
+ query: SET_WINE_IN_LIST_MUTATION,
+ variables: { wineId: '100062', list: 'WANT_TO_TRY', inList: false },
+ },
+ result: { data: { setWineInList: { __typename: 'Wine', id: '100062', myLists: [] } } },
+ },
+ ]);
+ await list();
+ await screen.findByTestId('auth-ready');
+
+ await user.click(screen.getByRole('button', { name: 'Vil prøve Origem Merlot' }));
+
+ expect(screen.getByText(/Du har ikke lagret noen viner ennå/)).toBeInTheDocument();
+ // The button the user clicked is gone. The live region says what happened,
+ // and focus moves to the heading of the list instead of the top of the page.
+ expect(screen.getByRole('status')).toHaveTextContent('Fjernet fra listen. Listen er tom.');
+ expect(screen.getByRole('heading', { level: 1, name: 'Vil prøve' })).toHaveFocus();
+ });
+
+ describe('when «Min side» has already fetched the first four', () => {
+ const six = ['1', '2', '3', '4', '5', '6'].map((id) => ({ id, name: `Vin ${id}` }));
+
+ /** A cache with the four wines «Min side» fetched, in the same place as the list page's. */
+ function cacheFromMyPage() {
+ const cache = createApolloCache();
+ const firstFour = page(six.slice(0, 4), { totalCount: 6, next: 'c4' });
+ cache.writeQuery({
+ query: MY_WINE_LIST_QUERY,
+ variables: { list: 'WANT_TO_TRY', first: 4 },
+ data: (firstFour.result as { data: Record }).data,
+ });
+ return cache;
+ }
+
+ it('shows those wines at once, while the whole first page is fetched', async () => {
+ // The answer is held back, so the page is seen before it arrives.
+ renderPage([{ ...page(six), delay: HELD_BACK }], '/mine/vil-prove', cacheFromMyPage());
+
+ expect(names(await list())).toEqual(['Vin 1', 'Vin 2', 'Vin 3', 'Vin 4']);
+ });
+
+ it('then shows the whole first page', async () => {
+ renderPage([page(six)], '/mine/vil-prove', cacheFromMyPage());
+
+ await waitFor(() => expect(names(screen.getByRole('list'))).toHaveLength(6));
+ expect(screen.queryByRole('button', { name: 'Last inn flere' })).not.toBeInTheDocument();
+ });
+ });
+
+ it('loads more wines, and moves focus to the first new one', async () => {
+ const { user } = renderPage([
+ page([{ id: '1', name: 'Første' }], { totalCount: 2, next: 'c1' }),
+ page([{ id: '2', name: 'Andre' }], { totalCount: 2, after: 'c1' }),
+ ]);
+ expect(names(await list())).toEqual(['Første']);
+ expect(screen.getByText('Viser 1 av 2 viner')).toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: 'Last inn flere' }));
+
+ await waitFor(() => expect(screen.getByRole('link', { name: 'Andre' })).toHaveFocus());
+ expect(names(screen.getByRole('list', { name: 'Viner du vil prøve' }))).toEqual([
+ 'Første',
+ 'Andre',
+ ]);
+ expect(screen.queryByRole('button', { name: 'Last inn flere' })).not.toBeInTheDocument();
+ });
+
+ it('offers a new attempt when the wines cannot be fetched', async () => {
+ renderPage([
+ {
+ request: {
+ query: MY_WINE_LIST_QUERY,
+ variables: { list: 'WANT_TO_TRY', first: LIST_PAGE_SIZE },
+ },
+ error: new Error('Nede'),
+ },
+ ]);
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('Vi fikk ikke hentet vinene');
+ expect(screen.getByRole('button', { name: 'Prøv igjen' })).toBeInTheDocument();
+ });
+
+ it('says so when the address is not one of the lists', async () => {
+ renderPage([], '/mine/finnes-ikke');
+ expect(
+ await screen.findByRole('heading', { level: 1, name: 'Fant ikke listen' }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Til Min side' })).toHaveAttribute('href', '/mine');
+ });
+
+ it('has no axe violations', async () => {
+ const { container } = renderPage([page([{ id: '100062', name: 'Origem Merlot' }])]);
+ await list();
+ expect(await axe(container)).toHaveNoViolations();
+ });
+});
diff --git a/frontend/src/features/my/MyListPage.tsx b/frontend/src/features/my/MyListPage.tsx
new file mode 100644
index 0000000..091d614
--- /dev/null
+++ b/frontend/src/features/my/MyListPage.tsx
@@ -0,0 +1,33 @@
+import { Link, useParams } from 'react-router';
+import { EmptyState } from '../../components/ui/EmptyState';
+import { useDocumentTitle } from '../../hooks/useDocumentTitle';
+import { useMyWineList } from '../lists/api/useMyWineList';
+import { listBySlug, type MyListInfo } from './myLists';
+import { MyListView } from './MyListView';
+
+/** Route component for `/mine/:list`, behind RequireAuth: one whole list, a page at a time. */
+export default function MyListPage() {
+ const info = listBySlug(useParams().list);
+ return info ? : ;
+}
+
+function KnownList({ info }: { info: MyListInfo }) {
+ useDocumentTitle(info.title);
+ return ;
+}
+
+function UnknownList() {
+ useDocumentTitle('Fant ikke listen');
+ return (
+
+ Til Min side}
+ >
+
Listene dine er Favoritter, Vil prøve og Har prøvd. Du finner alle på Min side.
+
+
+ );
+}
diff --git a/frontend/src/features/my/MyListView.module.css b/frontend/src/features/my/MyListView.module.css
new file mode 100644
index 0000000..51b3bb3
--- /dev/null
+++ b/frontend/src/features/my/MyListView.module.css
@@ -0,0 +1,35 @@
+.page {
+ display: grid;
+ gap: var(--space-4);
+ padding-block: var(--space-7);
+}
+
+.back {
+ justify-self: start;
+}
+
+.count,
+.empty {
+ color: var(--color-text-muted);
+}
+
+.more {
+ display: flex;
+ justify-content: center;
+ margin-top: var(--space-3);
+}
+
+.moreButton {
+ min-height: var(--tap-target);
+ padding: 0 var(--space-6);
+ border: 2px solid var(--color-link);
+ border-radius: var(--radius-pill);
+ background: transparent;
+ color: var(--color-text);
+ font-weight: 700;
+ cursor: pointer;
+}
+
+.moreButton:hover {
+ background: var(--color-surface-muted);
+}
diff --git a/frontend/src/features/my/MyListView.tsx b/frontend/src/features/my/MyListView.tsx
new file mode 100644
index 0000000..89a2f7c
--- /dev/null
+++ b/frontend/src/features/my/MyListView.tsx
@@ -0,0 +1,101 @@
+import { useEffect, useRef } from 'react';
+import { Link } from 'react-router';
+import { ErrorNotice } from '../../components/ui/ErrorNotice';
+import { Skeleton } from '../../components/ui/Skeleton';
+import { WineList } from '../../components/ui/WineList';
+import { formatCount, pluralize } from '../../lib/format';
+import { buildSearchUrl } from '../../lib/searchParams';
+import type { MyWineListResult } from '../lists/api/useMyWineList';
+import type { MyListInfo } from './myLists';
+import { useRemovalMessage } from './useRemovalMessage';
+import styles from './MyListView.module.css';
+
+interface MyListViewProps {
+ info: MyListInfo;
+ result: MyWineListResult;
+}
+
+/** Presentation of one whole list of the user's, newest first, with «Last inn flere». */
+export function MyListView({ info, result }: MyListViewProps) {
+ const { wines, totalCount, loading, loadingMore, hasNextPage, error, loadMoreError } = result;
+ const headingRef = useRef(null);
+ const message = useRemovalMessage(totalCount, headingRef);
+
+ // «Last inn flere» can disappear after the last page, so focus moves to the first new wine,
+ // where the user wants to go on reading. The same as on the search page.
+ const listRef = useRef(null);
+ const firstNewWine = useRef(null);
+ useEffect(() => {
+ if (loadingMore || firstNewWine.current === null) return;
+ const index = firstNewWine.current;
+ firstNewWine.current = null;
+ listRef.current?.children[index]?.querySelector('a')?.focus();
+ }, [loadingMore, wines.length]);
+
+ function loadMore() {
+ firstNewWine.current = wines.length;
+ void result.loadMore();
+ }
+
+ return (
+
+ {/* The number is text, so screen readers in Safari, which drop the numbers of a
+ list with role="list", still say which place it is. */}
+ {place}.
+ {wine ? (
+ <>
+
+
+
+
+
+ {wine.name}
+
+
+
+ {WINE_TYPES[wine.type].label} · {wine.winery}
+
+ >
+ ) : (
+
Ledig plass
+ )}
+
+ );
+ })}
+
+
+ {wines.length === 0 && (
+
+ {hasFavourites
+ ? 'Du har ikke valgt topp 4 ennå. Velg dem med «Endre topp 4».'
+ : 'Topp 4 velger du blant favorittene dine, og du har ingen ennå. Trykk på hjertet på en vin for å legge den til.'}
+
+ )}
+
+ {hasFavourites && (
+
+
+
+ )}
+ >
+ )}
+
+ );
+}
diff --git a/frontend/src/features/my/components/TopFavouritesEditor.module.css b/frontend/src/features/my/components/TopFavouritesEditor.module.css
new file mode 100644
index 0000000..43dce1f
--- /dev/null
+++ b/frontend/src/features/my/components/TopFavouritesEditor.module.css
@@ -0,0 +1,89 @@
+.editor {
+ display: grid;
+ gap: var(--space-3);
+}
+
+.editor h3:focus-visible {
+ outline: 3px solid var(--color-focus);
+ outline-offset: 2px;
+}
+
+.muted {
+ color: var(--color-text-muted);
+}
+
+.rows {
+ display: grid;
+ gap: var(--space-2);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2) var(--space-3);
+ padding: var(--space-2) var(--space-3);
+ border-radius: var(--radius-md);
+ background: var(--color-surface);
+}
+
+.place {
+ min-width: 1.5rem;
+ font-weight: 700;
+}
+
+.name {
+ flex: 1 1 12rem;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+
+.actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+}
+
+.rowButton,
+.secondary,
+.primary {
+ min-height: var(--tap-target);
+ padding: 0 var(--space-4);
+ border: 2px solid var(--color-link);
+ border-radius: var(--radius-pill);
+ background: transparent;
+ color: var(--color-text);
+ font-weight: 700;
+ cursor: pointer;
+}
+
+.rowButton:hover,
+.secondary:hover {
+ background: var(--color-surface-muted);
+}
+
+.primary {
+ border-color: var(--color-brand);
+ background: var(--color-brand);
+ color: var(--white);
+}
+
+.primary:hover {
+ background: var(--color-brand-strong);
+}
+
+/* A button that does nothing right now still has focus, but looks it. */
+.rowButton[aria-disabled='true'],
+.primary[aria-disabled='true'] {
+ opacity: 0.55;
+ cursor: not-allowed;
+}
+
+.buttons {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-3);
+}
diff --git a/frontend/src/features/my/components/TopFavouritesEditor.tsx b/frontend/src/features/my/components/TopFavouritesEditor.tsx
new file mode 100644
index 0000000..77ce59d
--- /dev/null
+++ b/frontend/src/features/my/components/TopFavouritesEditor.tsx
@@ -0,0 +1,286 @@
+import { useEffect, useId, useRef, useState } from 'react';
+import { useMutation } from '@apollo/client/react';
+import { ErrorNotice } from '../../../components/ui/ErrorNotice';
+import { classifyError } from '../../../lib/errors';
+import { focusIfLost } from '../../../lib/focus';
+import type { WineSummary } from '../../../lib/types';
+import { useMyWineList } from '../../lists/api/useMyWineList';
+import { SET_TOP_FAVOURITES_MUTATION } from '../api/topFavouritesMutation';
+import { addWine, MAX_TOP_FAVOURITES, moveWine, removeWine } from '../topFavouritesDraft';
+import styles from './TopFavouritesEditor.module.css';
+
+interface TopFavouritesEditorProps {
+ /** The top 4 as it is saved now, in order. */
+ current: WineSummary[];
+ onSaved: () => void;
+ onCancel: () => void;
+}
+
+/**
+ * Choosing the top 4 among the favourites, with buttons only: no drag and drop, so it works the
+ * same with a keyboard, a screen reader, a switch or a finger. Nothing is saved before
+ * «Lagre topp 4»; «Avbryt» leaves the top 4 as it was.
+ *
+ * Each change is read out in a live region. Focus stays on the button the user pressed, or, when
+ * that button is gone, moves to the nearest one in the same list.
+ */
+export function TopFavouritesEditor({ current, onSaved, onCancel }: TopFavouritesEditorProps) {
+ const [draft, setDraft] = useState(current);
+ const [announcement, setAnnouncement] = useState('');
+ const [saveError, setSaveError] = useState(null);
+ const favourites = useMyWineList('FAVOURITE');
+ const [saveTop, { loading: saving }] = useMutation(SET_TOP_FAVOURITES_MUTATION);
+
+ const id = useId();
+ const headingRef = useRef(null);
+ const draftRef = useRef(null);
+ const choicesRef = useRef(null);
+ /** Where focus goes after the next render, if the focused button was removed by it. */
+ const focusAfterRender = useRef<(() => Element | null | undefined) | null>(null);
+
+ // The editor replaces the top 4, like a new part of the page, so focus moves to its heading.
+ useEffect(() => headingRef.current?.focus(), []);
+
+ useEffect(() => {
+ const find = focusAfterRender.current;
+ if (!find) return;
+ focusAfterRender.current = null;
+ const target = find();
+ if (target instanceof HTMLElement) focusIfLost(target);
+ });
+
+ const chosen = new Set(draft.map((wine) => wine.id));
+ const choices = favourites.wines.filter((wine) => !chosen.has(wine.id));
+ const full = draft.length >= MAX_TOP_FAVOURITES;
+
+ // «Vis flere favoritter» disappears after the last page, so focus moves to the first new
+ // favourite, as on the list pages.
+ const firstNewChoice = useRef(null);
+ useEffect(() => {
+ if (favourites.loadingMore || firstNewChoice.current === null) return;
+ const index = firstNewChoice.current;
+ firstNewChoice.current = null;
+ const target = choicesRef.current?.children[index]?.querySelector('button');
+ if (target) focusIfLost(target);
+ }, [favourites.loadingMore, choices.length]);
+
+ function loadMoreChoices() {
+ firstNewChoice.current = choices.length;
+ void favourites.loadMore();
+ }
+
+ /** The button with `action` in row `index` of a list, or in the row before it. */
+ const button = (list: HTMLElement | null, index: number, action: string) =>
+ list?.children[index]?.querySelector(`[data-action="${action}"]`) ??
+ list?.children[index - 1]?.querySelector(`[data-action="${action}"]`);
+
+ function move(index: number, by: -1 | 1) {
+ const next = moveWine(draft, index, by);
+ if (next === draft) return;
+ setDraft(next);
+ setAnnouncement(`${draft[index].name} er flyttet til plass ${index + by + 1}.`);
+ // React may move the row in the page, and a moved element can lose focus.
+ const action = by < 0 ? 'up' : 'down';
+ focusAfterRender.current = () => button(draftRef.current, index + by, action);
+ }
+
+ function remove(index: number) {
+ const wine = draft[index];
+ setDraft(removeWine(draft, index));
+ setAnnouncement(`${wine.name} er tatt ut av topp 4.`);
+ focusAfterRender.current = () =>
+ button(draftRef.current, index, 'remove') ?? headingRef.current;
+ }
+
+ function add(wine: WineSummary, index: number) {
+ if (full) return;
+ setDraft(addWine(draft, wine));
+ setAnnouncement(`${wine.name} er lagt til på plass ${draft.length + 1}.`);
+ focusAfterRender.current = () =>
+ button(choicesRef.current, index, 'add') ?? button(draftRef.current, draft.length, 'remove');
+ }
+
+ async function save() {
+ if (saving) return;
+ setSaveError(null);
+ try {
+ await saveTop({ variables: { wineIds: draft.map((wine) => wine.id) } });
+ onSaved();
+ } catch (error) {
+ setSaveError(error);
+ }
+ }
+
+ return (
+
+
+ Endre topp 4
+
+
+ Velg opptil fire av favorittene dine, og sett dem i den rekkefølgen du vil.
+
+ )}
+
+ {saveError !== null && (
+
+ )}
+
+ {/* Layout only: the two buttons that end the editing. */}
+
+
+
+
+
+ );
+}
+
+interface RowButtonProps {
+ action: 'up' | 'down' | 'remove' | 'add';
+ label: string;
+ /**
+ * In the accessible name after the visible text, so «Flytt opp Origem Merlot» says which wine,
+ * and voice control still finds the button by the words on it (WCAG 2.5.3). An aria-label, not
+ * hidden text: browsers join hidden text to the visible text in different ways.
+ */
+ wine: string;
+ disabled?: boolean;
+ describedBy?: string;
+ onClick: () => void;
+}
+
+/**
+ * aria-disabled instead of disabled: a disabled button cannot have focus, so the focus would be
+ * lost when a wine is moved to the top and its «Flytt opp» stops working.
+ */
+function RowButton({
+ action,
+ label,
+ wine,
+ disabled = false,
+ describedBy,
+ onClick,
+}: RowButtonProps) {
+ return (
+
+ );
+}
diff --git a/frontend/src/features/my/myLists.ts b/frontend/src/features/my/myLists.ts
new file mode 100644
index 0000000..9749b1e
--- /dev/null
+++ b/frontend/src/features/my/myLists.ts
@@ -0,0 +1,56 @@
+import { pluralize } from '../../lib/format';
+import type { WineListName } from '../../lib/wineLists';
+
+/** What «Min side» and the list pages say about each list. */
+export interface MyListInfo {
+ list: WineListName;
+ /** The path under /mine, in Norwegian like the other addresses on the site. */
+ slug: string;
+ title: string;
+ /** The name of the list of cards, for screen readers. */
+ label: string;
+ /** Shown when the list is empty: how to add a wine to it. */
+ empty: string;
+ /** The text of the link from «Min side» to the whole list. «Se alle 1 …» reads oddly, so one has its own. */
+ seeAll: (count: number) => string;
+}
+
+export const MY_LISTS: MyListInfo[] = [
+ {
+ list: 'FAVOURITE',
+ slug: 'favoritter',
+ title: 'Favoritter',
+ label: 'Favorittene dine',
+ empty: 'Du har ingen favoritter ennå. Trykk på hjertet på en vin for å legge den her.',
+ seeAll: (count) =>
+ count === 1 ? 'Se favoritten' : `Se alle ${pluralize(count, 'favoritt', 'favoritter')}`,
+ },
+ {
+ list: 'WANT_TO_TRY',
+ slug: 'vil-prove',
+ title: 'Vil prøve',
+ label: 'Viner du vil prøve',
+ empty: 'Du har ikke lagret noen viner ennå. Trykk på bokmerket på en vin for å legge den her.',
+ seeAll: (count) =>
+ count === 1
+ ? 'Se vinen du vil prøve'
+ : `Se alle ${pluralize(count, 'vin', 'viner')} du vil prøve`,
+ },
+ {
+ list: 'TRIED',
+ slug: 'har-provd',
+ title: 'Har prøvd',
+ label: 'Viner du har prøvd',
+ empty:
+ 'Du har ikke merket noen viner som prøvd ennå. Trykk «Har prøvd» på siden til en vin, eller gi vinen din dom.',
+ seeAll: (count) =>
+ count === 1
+ ? 'Se vinen du har prøvd'
+ : `Se alle ${pluralize(count, 'vin', 'viner')} du har prøvd`,
+ },
+];
+
+/** The list with this path, or undefined for a path that is not a list. */
+export function listBySlug(slug: string | undefined): MyListInfo | undefined {
+ return MY_LISTS.find((info) => info.slug === slug);
+}
diff --git a/frontend/src/features/my/topFavouritesDraft.test.ts b/frontend/src/features/my/topFavouritesDraft.test.ts
new file mode 100644
index 0000000..a075f6b
--- /dev/null
+++ b/frontend/src/features/my/topFavouritesDraft.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+import type { WineSummary } from '../../lib/types';
+import { addWine, moveWine, removeWine } from './topFavouritesDraft';
+
+const wine = (id: string) => ({ id, name: `Vin ${id}` }) as WineSummary;
+const ids = (draft: WineSummary[]) => draft.map((chosen) => chosen.id);
+const draft = ['1', '2', '3'].map(wine);
+
+describe('moveWine', () => {
+ it('moves a wine one place up or down', () => {
+ expect(ids(moveWine(draft, 1, -1))).toEqual(['2', '1', '3']);
+ expect(ids(moveWine(draft, 1, 1))).toEqual(['1', '3', '2']);
+ });
+
+ it('leaves the list as it is at the top and the bottom', () => {
+ expect(moveWine(draft, 0, -1)).toBe(draft);
+ expect(moveWine(draft, 2, 1)).toBe(draft);
+ });
+});
+
+describe('addWine', () => {
+ it('adds a wine at the end', () => {
+ expect(ids(addWine(draft, wine('9')))).toEqual(['1', '2', '3', '9']);
+ });
+
+ it('adds no fifth wine, and no wine twice', () => {
+ const full = addWine(draft, wine('4'));
+ expect(addWine(full, wine('5'))).toBe(full);
+ expect(addWine(draft, wine('2'))).toBe(draft);
+ });
+});
+
+describe('removeWine', () => {
+ it('takes a wine out, and the others move up', () => {
+ expect(ids(removeWine(draft, 0))).toEqual(['2', '3']);
+ });
+});
diff --git a/frontend/src/features/my/topFavouritesDraft.ts b/frontend/src/features/my/topFavouritesDraft.ts
new file mode 100644
index 0000000..6ce0e06
--- /dev/null
+++ b/frontend/src/features/my/topFavouritesDraft.ts
@@ -0,0 +1,27 @@
+import type { WineSummary } from '../../lib/types';
+
+/** The same limit as the API's MAX_TOP_FAVOURITES. */
+export const MAX_TOP_FAVOURITES = 4;
+
+/**
+ * Small, pure steps for the top 4 the user is editing, so the rules are tested apart from the
+ * buttons. Each returns a new list, or the same list when the step is not possible.
+ */
+export function moveWine(draft: WineSummary[], index: number, by: -1 | 1): WineSummary[] {
+ const target = index + by;
+ if (index < 0 || index >= draft.length || target < 0 || target >= draft.length) return draft;
+ const next = [...draft];
+ [next[index], next[target]] = [next[target], next[index]];
+ return next;
+}
+
+export function addWine(draft: WineSummary[], wine: WineSummary): WineSummary[] {
+ if (draft.length >= MAX_TOP_FAVOURITES || draft.some((chosen) => chosen.id === wine.id)) {
+ return draft;
+ }
+ return [...draft, wine];
+}
+
+export function removeWine(draft: WineSummary[], index: number): WineSummary[] {
+ return draft.filter((_, position) => position !== index);
+}
diff --git a/frontend/src/features/my/useRemovalMessage.ts b/frontend/src/features/my/useRemovalMessage.ts
new file mode 100644
index 0000000..3794d8a
--- /dev/null
+++ b/frontend/src/features/my/useRemovalMessage.ts
@@ -0,0 +1,37 @@
+import { useEffect, useRef, useState, type RefObject } from 'react';
+import { focusIfLost } from '../../lib/focus';
+import { pluralize } from '../../lib/format';
+
+/**
+ * When a wine is taken off a list on the page, its card disappears, and with it the button the
+ * user pressed. Returns the text for a live region that says so, and moves focus to `heading`,
+ * so keyboard and screen reader users are not left at the top of the page.
+ *
+ * `count` is the number of wines on the list, or undefined while it is loading.
+ */
+export function useRemovalMessage(
+ count: number | undefined,
+ heading: RefObject,
+): string {
+ const [previous, setPrevious] = useState(count);
+ const [message, setMessage] = useState('');
+
+ if (count !== previous) {
+ setPrevious(count);
+ const removed = count !== undefined && previous !== undefined && count < previous;
+ setMessage(
+ removed
+ ? `Fjernet fra listen. ${count === 0 ? 'Listen er tom.' : `${pluralize(count, 'vin', 'viner')} igjen.`}`
+ : '',
+ );
+ }
+
+ const before = useRef(count);
+ useEffect(() => {
+ const last = before.current;
+ before.current = count;
+ if (count !== undefined && last !== undefined && count < last) focusIfLost(heading.current);
+ }, [count, heading]);
+
+ return message;
+}
diff --git a/frontend/src/features/wine/WinePage.test.tsx b/frontend/src/features/wine/WinePage.test.tsx
index db1b789..556d0b9 100644
--- a/frontend/src/features/wine/WinePage.test.tsx
+++ b/frontend/src/features/wine/WinePage.test.tsx
@@ -253,6 +253,16 @@ describe('WinePage – tilbakelenke', () => {
expect(screen.getByRole('link', { name: 'Tilbake til forsiden' })).toHaveAttribute('href', '/');
});
+ it.each([
+ ['/mine', 'Tilbake til Min side'],
+ ['/mine/favoritter', 'Tilbake til listen'],
+ ['/mine/dommer?sortering=eldste', 'Tilbake til Mine dommer'],
+ ])('går tilbake til %s', async (from, label) => {
+ renderPage([found()], { pathname: '/vin/100062', state: { from } });
+ await heading();
+ expect(screen.getByRole('link', { name: label })).toHaveAttribute('href', from);
+ });
+
it('lenker til alle viner ved direkte besøk', async () => {
renderPage([found()]);
await heading();
@@ -262,7 +272,7 @@ describe('WinePage – tilbakelenke', () => {
);
});
- it.each(['https://evil.example', '//evil.example', 42])(
+ it.each(['https://evil.example', '//evil.example', 42, '/mine/../konto', '/mine/x?a='])(
'ignorerer ugyldig tilstand: %s',
async (from) => {
renderPage([found()], { pathname: '/vin/100062', state: { from } });
diff --git a/frontend/src/features/wine/WineView.tsx b/frontend/src/features/wine/WineView.tsx
index b6c0270..e69a636 100644
--- a/frontend/src/features/wine/WineView.tsx
+++ b/frontend/src/features/wine/WineView.tsx
@@ -29,6 +29,15 @@ function backLink(state: unknown) {
if (from === '/sok' || (typeof from === 'string' && from.startsWith('/sok?'))) {
return { to: from, label: 'Tilbake til søket' };
}
+ if (from === '/mine') return { to: from, label: 'Tilbake til Min side' };
+ // A list or the reviews on «Min side», with the order in the URL: /mine/favoritter,
+ // /mine/dommer?sortering=eldste. Only letters, digits and dashes, so it stays on the site.
+ if (typeof from === 'string' && /^\/mine\/[a-z-]+(\?[a-z0-9=&-]*)?$/.test(from)) {
+ return {
+ to: from,
+ label: from.startsWith('/mine/dommer') ? 'Tilbake til Mine dommer' : 'Tilbake til listen',
+ };
+ }
return ALL_WINES;
}
diff --git a/frontend/src/features/wine/api/useWineReviews.ts b/frontend/src/features/wine/api/useWineReviews.ts
index a852f4a..ad50359 100644
--- a/frontend/src/features/wine/api/useWineReviews.ts
+++ b/frontend/src/features/wine/api/useWineReviews.ts
@@ -1,4 +1,6 @@
+import type { ApolloCache } from '@apollo/client';
import { useMutation, useQuery } from '@apollo/client/react';
+import { useAuth } from '../../auth/useAuth';
import type { RatingSummary } from '../../../lib/types';
import {
DELETE_REVIEW_MUTATION,
@@ -34,6 +36,7 @@ export interface WineReviewsResult {
/** The student reviews of one wine, and functions to save or delete the user's own review. */
export function useWineReviews(wineId: string): WineReviewsResult {
+ const { user } = useAuth();
const { data, loading, error, refetch } = useQuery(WINE_REVIEWS_QUERY, {
variables: { id: wineId },
});
@@ -45,18 +48,25 @@ export function useWineReviews(wineId: string): WineReviewsResult {
awaitRefetchQueries: true,
};
+ // Also the user's own reviews on «Min side», and the lists: a saved review puts the wine on
+ // «Har prøvd» and takes it off «Vil prøve». They are fetched again the next time they are shown.
+ function forgetChangedLists(cache: ApolloCache) {
+ cache.evict({ fieldName: 'recentReviews' });
+ const me = user && cache.identify({ __typename: 'User', id: user.id });
+ if (me) {
+ cache.evict({ id: me, fieldName: 'reviews' });
+ cache.evict({ id: me, fieldName: 'wines' });
+ }
+ }
+
const [saveReview, saveState] = useMutation(SAVE_REVIEW_MUTATION, {
...afterChange,
- update(cache) {
- cache.evict({ fieldName: 'recentReviews' });
- },
+ update: forgetChangedLists,
});
const [deleteReview, deleteState] = useMutation(DELETE_REVIEW_MUTATION, {
...afterChange,
- update(cache) {
- cache.evict({ fieldName: 'recentReviews' });
- },
+ update: forgetChangedLists,
});
async function save({ rating, comment }: ReviewDraft): Promise {
diff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.ts
index ac176ec..705ce6a 100644
--- a/frontend/src/lib/apollo.ts
+++ b/frontend/src/lib/apollo.ts
@@ -2,7 +2,10 @@ import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/clien
import { CombinedGraphQLErrors } from '@apollo/client/errors';
import { ErrorLink } from '@apollo/client/link/error';
-/** A page of the `wines` field as it is stored in the Apollo cache. */
+/**
+ * A page of the `wines` field as it is stored in the Apollo cache. The user's `reviews` have the
+ * same shape, with reviews instead of wines, so they are merged the same way.
+ */
export interface WineConnection {
totalCount: number;
edges: { cursor: string; node: { __ref: string } }[];
@@ -43,6 +46,13 @@ export function createApolloCache() {
return mergeWineConnection(existing, incoming, args?.after as string | undefined);
},
},
+ // The user's reviews, one list per order, with the pages added after each other.
+ reviews: {
+ keyArgs: ['order'],
+ merge(existing: WineConnection | undefined, incoming: WineConnection, { args }) {
+ return mergeWineConnection(existing, incoming, args?.after as string | undefined);
+ },
+ },
},
},
Query: {
diff --git a/frontend/src/lib/format.test.ts b/frontend/src/lib/format.test.ts
index b04e7ac..4df7882 100644
--- a/frontend/src/lib/format.test.ts
+++ b/frontend/src/lib/format.test.ts
@@ -4,6 +4,7 @@ import {
formatAbv,
formatCount,
formatCountry,
+ formatMonthYear,
formatRating,
formatRatingSummary,
formatRelativeTime,
@@ -89,3 +90,13 @@ describe('formatAuthor', () => {
expect(formatAuthor(null)).toBe('Anonym student');
});
});
+
+describe('formatMonthYear', () => {
+ it('gives the month and year in Norwegian', () => {
+ expect(formatMonthYear('2026-11-19T12:00:00.000Z')).toBe('november 2026');
+ });
+
+ it('uses Norwegian time, so the last hour of a month in UTC is the next month', () => {
+ expect(formatMonthYear('2026-10-31T23:30:00.000Z')).toBe('november 2026');
+ });
+});
diff --git a/frontend/src/lib/format.ts b/frontend/src/lib/format.ts
index 2f5820d..4f3551d 100644
--- a/frontend/src/lib/format.ts
+++ b/frontend/src/lib/format.ts
@@ -63,6 +63,17 @@ export function formatRatingSummary(
return `${formatRating(summary.average)} av ${scale} · ${pluralize(summary.count, singular, plural)}`;
}
+const monthYearFormatter = new Intl.DateTimeFormat(LOCALE, {
+ month: 'long',
+ year: 'numeric',
+ timeZone: 'Europe/Oslo',
+});
+
+/** «2026-11-19T12:00:00Z» → «november 2026». In Norwegian time, so the month is the user's. */
+export function formatMonthYear(iso: string): string {
+ return monthYearFormatter.format(new Date(iso));
+}
+
const relativeFormatter = new Intl.RelativeTimeFormat(LOCALE, { numeric: 'auto' });
const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
diff --git a/frontend/src/lib/wineLists.ts b/frontend/src/lib/wineLists.ts
index 5f99ff4..9e5c2ef 100644
--- a/frontend/src/lib/wineLists.ts
+++ b/frontend/src/lib/wineLists.ts
@@ -6,6 +6,7 @@ export type WineListName = (typeof WINE_LISTS)[number];
* The lists a wine is on after putting it on `list` (inList: true) or taking it off. The same
* rules as the API, so the buttons can change at once, before the answer comes:
* «Har prøvd» takes the wine off «Vil prøve», and the order is fixed, as in the API.
+ * The API's version is in backend/src/lists/wine-lists.ts: change both together.
*/
export function listsAfterChange(
current: readonly WineListName[],
diff --git a/frontend/src/test/heldBack.ts b/frontend/src/test/heldBack.ts
new file mode 100644
index 0000000..05bd987
--- /dev/null
+++ b/frontend/src/test/heldBack.ts
@@ -0,0 +1,6 @@
+/**
+ * A delay for a fake API answer the test never waits for. The request stays on its way for the
+ * rest of the test, so the test can look at the page before the answer without depending on how
+ * fast the computer is.
+ */
+export const HELD_BACK = 10_000;
diff --git a/test-results/.last-run.json b/test-results/.last-run.json
deleted file mode 100644
index 5fca3f8..0000000
--- a/test-results/.last-run.json
+++ /dev/null
@@ -1,4 +0,0 @@
-{
- "status": "failed",
- "failedTests": []
-}
\ No newline at end of file