diff --git a/README.md b/README.md index 23d718c..674a0fd 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Kork & Krone -**Last updated:** 18 November 2026 +**Last updated:** 19 November 2026 **Submission:** 4 (working system, ready for feedback on every aspect) **Status:** In progress. See [Status for submission 4](#status-for-submission-4). @@ -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 «Vil prøve» list. Own reviews come with login in the interface | +| «Mine anmeldelser» page | Done | Shows the user's «Vil prøve» list from the API, behind login. Own reviews come with the profile page | | 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 | Backend done | API and rules in [API](docs/api.md#wine-lists). The interface comes next | +| 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) | | 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 | @@ -108,9 +108,14 @@ To try the features that need login without registering, log in at `/konto` with | `demo` | `kork-og-krone` | The user has favourites with a top 4, wines on «Vil prøve» and «Har prøvd», and some reviews. It exists -on the VM, and locally after `npm run db:seed:demo`, which also resets it if someone has changed it. -Everyone can see the password, so do not store anything private on this user. Searching and reading -reviews never require login. +on the VM, and locally after `npm run db:seed:demo`. + +Everyone with the link can log in as `demo` and change its lists and reviews, and the lists are +public. Do not store anything private on this user. If someone has left it in a strange state, run +`npm run db:seed:demo` in `backend/` (on the VM too): it puts the lists, the reviews and the password +back as they were. + +Searching and reading reviews never require login. ## Features @@ -126,8 +131,8 @@ 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 | -| Wishlist ("Vil prøve") | Done | Done | Saved in the browser and shown on «Mine anmeldelser». The interface moves to the backend list next | -| Favourites, top 4 and «Har prøvd» | Done | Planned | Stored per user and public. «Har prøvd» takes a wine off «Vil prøve», and a saved review marks the wine as tried. See [API](docs/api.md#wine-lists) | +| 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 | | 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 | @@ -160,6 +165,8 @@ Each row explains what we chose, why, and what else we considered. Added as the | Pagination | GraphQL connection with an opaque cursor that holds an offset. Pages are merged in the Apollo cache | Simple, and works with every sort order. The frontend never reads the cursor, so we can switch to keyset pagination later without changing it | Keyset pagination: faster deep into large results, but harder to combine with many sort orders | | 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 | +| 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 | | Filter panel on small screens | Native `` with `showModal()` | The browser handles focus trapping, Escape and returning focus, with no extra JavaScript | A dialog library | @@ -236,6 +243,7 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing, - 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. +- 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. - 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. @@ -298,9 +306,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 wishlist page, loading, empty and error states, and axe on each component | 269 in 28 files | +| 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, and no axe violations (WCAG 2.1 AA) | 50 (24 tests in 2 browser projects, and 2 for mobile only) | +| 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) | | 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`. @@ -392,9 +400,9 @@ 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). -- [ ] The lists in the interface: heart, bookmark and «Har prøvd» on the wines. +- [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. -- [ ] Wishlist stored in the backend, so it follows the user between devices. The API is ready. +- [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. - [ ] Measure sustainability and fill in the budget table. @@ -407,7 +415,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 wishlist. +- [x] «Mine anmeldelser» with the «Vil prøve» list from the API. - [x] User accounts in the backend. - [x] Database migrations. - [x] Larger dataset on the VM. diff --git a/backend/src/lists/lists-api.db.test.ts b/backend/src/lists/lists-api.db.test.ts index 91b8181..7024192 100644 --- a/backend/src/lists/lists-api.db.test.ts +++ b/backend/src/lists/lists-api.db.test.ts @@ -83,6 +83,18 @@ describe.skipIf(!url)('wine lists API (PostgreSQL)', () => { expect(pageOf(await per.request(LIST, { list: 'WANT_TO_TRY' })).totalCount).toBe(0); }); + it('lets a tried wine go back on «Vil prøve», so it is on both lists', async () => { + // A choice, not an accident: the user may want to taste it again. Only «Har prøvd» + // moves a wine between the two lists, not «Vil prøve». + const [wine] = await api.createWines(1); + const eli = await api.createBrowser('eli'); + await eli.request(SET, set(wine, 'TRIED')); + + const result = await eli.request(SET, set(wine, 'WANT_TO_TRY')); + + expect(listsOf(result).myLists).toEqual(['WANT_TO_TRY', 'TRIED']); + }); + it('keeps the lists of each user apart', async () => { const [wine] = await api.createWines(1); const anne = await api.createBrowser('anne'); diff --git a/docs/api.md b/docs/api.md index 7e8e404..902791d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -51,6 +51,12 @@ query { During development, Vite forwards `/graphql` to the backend. On the VM, Apache forwards `/project2/graphql`. Use `${import.meta.env.BASE_URL}graphql` as the endpoint so both work. +When any request answers `UNAUTHENTICATED`, the session has ended while the page was open (it +expired, or the user logged out in another tab). A link in `lib/apollo.ts` then fetches `me` again, +so the header, the review form and the list buttons all show that nobody is logged in. After a +login or logout, `AuthProvider` calls `resetStore()`, which empties the cache and fetches the +queries on the page again, `me` included, with the new cookie. + ## Tests `npm test` in `backend/` runs the unit tests. The API tests that need PostgreSQL are described @@ -227,6 +233,7 @@ The table `user_wine` has one row per user, list and wine: `id`, `user_id`, `win |---|---| | A wine is at most once on each list | `UNIQUE (user_id, list, wine_id)`. Adding it again changes nothing | | A wine can be on several lists, such as a favourite that is also tried | No rule against it | +| A tried wine can go back on «Vil prøve», and is then on both | A choice: the user may want to taste it again, for example another vintage. Only putting a wine on «Har prøvd» moves it, not the other way. Tested in `lists-api.db.test.ts` and `lib/wineLists.test.ts` | | «Har prøvd» takes the wine off «Vil prøve» | `setWineInList` in `wine-lists.ts`, in the same transaction | | A saved review puts the wine on «Har prøvd» | `saveReview`, in the same transaction as the review. Deleting the review keeps the wine on «Har prøvd» | | The top 4 has at most four wines, each once, all favourites | `setTopFavourites` checks and gives a clear error. The database checks it too: `top_position BETWEEN 1 AND 4`, a unique index on `(user_id, top_position)`, and `CHECK (top_position IS NULL OR list = 'FAVOURITE')` | @@ -275,6 +282,24 @@ Choices and why: | `lists/lists-api.db.test.ts` | Through Apollo Server against PostgreSQL: login required, adding and removing twice, several lists, «Har prøvd» takes the wine off «Vil prøve», users kept apart, unknown wines and lists, pages that do not skip, one query for `myLists` on a page of 24, the top 4 rules and order, two changes at once, the database constraints, and that a saved review marks the wine as tried | | `demo/demo-user.db.test.ts` | The demo user: the documented password works, the data follows the rules, the averages are updated, and running it again gives the same state | +### In the frontend + +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 | +| `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 | +| `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 | + +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. + ## Demo user `npm run db:seed:demo` in `backend/` creates the user **`demo`** with the password **`kork-og-krone`**, @@ -299,6 +324,19 @@ cd backend DATABASE_URL=postgresql://vinmonopolet_app:PASSWORD@localhost:5432/vinmonopolet_test npm run db:migrate ``` +The migration uses `DATABASE_URL`, so it is set to the test database for this one command. The +variable set in the command wins over the one in `backend/.env`. On Windows PowerShell, which does +not understand `NAME=value command`, set it first and remove it afterwards, so the next migration +goes to your own database again: + +```powershell +$env:DATABASE_URL="postgresql://vinmonopolet_app:PASSWORD@localhost:5432/vinmonopolet_test" +npm run db:migrate +Remove-Item Env:DATABASE_URL +``` + +Run the same command for the test database every time you pull a new migration. + Then run all tests, including the database tests: ```bash @@ -306,6 +344,5 @@ TEST_DATABASE_URL=postgresql://vinmonopolet_app:PASSWORD@localhost:5432/vinmonop ``` On Windows PowerShell, set the variable first: `$env:TEST_DATABASE_URL="postgresql://..."`, then `npm test`. -Run the migration again after pulling a new migration. See [manual testing](manual-testing.md) for how to test users and user data by hand. diff --git a/docs/manual-testing.md b/docs/manual-testing.md index f50b7af..6e1b1a4 100644 --- a/docs/manual-testing.md +++ b/docs/manual-testing.md @@ -41,6 +41,7 @@ cd frontend && npm run dev # terminal 2, http://localho |---|---| | Reload the page | Still logged in | | Restart the backend (Ctrl+C, `npm run dev`) and reload | Still logged in, because the session is in the database | +| `DELETE FROM user_session;` in psql, then save a review without reloading | The error message, and the header shows «Logg inn» at once: the page fetched `me` again | | Log out on `/konto` | The menu shows «Logg inn». The row in `user_session` is gone | ## 3. Reviews @@ -90,10 +91,31 @@ Things that should fail: | `UPDATE user_session SET expires_at = now() - interval '1 minute';` and reload | Treated as logged out | | `DELETE FROM app_user WHERE username = 'test_ola';` | The user's sessions and reviews go too (`ON DELETE CASCADE`) | -## 5. Wine lists and the top 4 +## 5. Wine lists in the interface -The interface for the lists comes later, so test them through the API. Log in with curl as in section 4, -then define a short helper and pick a wine: +| Step | Expected | +|---|---| +| 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» | +| 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 | + +## 6. Moving an old «Vil prøve» list + +Before login, «Vil prøve» was stored in the browser. It moves to the first user who logs in there. + +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. +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 + +Log in with curl as in section 4, then define a short helper and pick a wine: ```bash q() { curl -s -b /tmp/kk.jar $API -H "$H" -d "{\"query\":\"$1\"}"; echo; } @@ -114,7 +136,7 @@ echo "VIN=$VIN" | The mutations without the cookie (leave out `-b /tmp/kk.jar`) | `UNAUTHENTICATED` | | `SELECT list, wine_id, top_position FROM user_wine WHERE user_id = (SELECT id FROM app_user WHERE username = 'test_curl');` | The same as the API shows | -## 6. The demo user +## 8. The demo user | Step | Expected | |---|---| @@ -122,7 +144,7 @@ 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 | -## 7. Accessibility +## 9. Accessibility | Step | Expected | |---|---| diff --git a/frontend/e2e/filters.spec.ts b/frontend/e2e/filters.spec.ts index 9b6d06f..d5d0250 100644 --- a/frontend/e2e/filters.spec.ts +++ b/frontend/e2e/filters.spec.ts @@ -22,6 +22,7 @@ const wine = (id: number, type: string) => ({ wineryName: 'Testprodusent', communityRating: 4, communityRatingCount: 10, + myLists: [], }); function winesResponse({ filter, sort }: Variables) { diff --git a/frontend/e2e/landing.spec.ts b/frontend/e2e/landing.spec.ts index 9a1dbab..d2c7268 100644 --- a/frontend/e2e/landing.spec.ts +++ b/frontend/e2e/landing.spec.ts @@ -17,6 +17,7 @@ const wines = Array.from({ length: 6 }, (_, i) => ({ wineryName: 'Testprodusent', communityRating: 4.5, communityRatingCount: 10, + myLists: [], })); const landingResponse = { diff --git a/frontend/e2e/lists.spec.ts b/frontend/e2e/lists.spec.ts new file mode 100644 index 0000000..0acb95f --- /dev/null +++ b/frontend/e2e/lists.spec.ts @@ -0,0 +1,207 @@ +import AxeBuilder from '@axe-core/playwright'; +import { expect, test, type Page } from '@playwright/test'; +import { stubGraphQL } from './support/graphql'; + +/* + * E2E for the wine lists: the buttons on the wine cards and the wine page, «Mine anmeldelser», + * 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. + */ +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 ({ + page, + }) => { + await fakeApi(page); + await page.goto('./sok'); + await loggedIn(page); + + // With the keyboard only. + const bookmark = page.getByRole('button', { name: 'Vil prøve Rødvin 2' }); + await bookmark.focus(); + await page.keyboard.press('Enter'); + 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 expect(myList(page).getByRole('link')).toHaveText(['Rødvin 2']); + await expectNoAxeViolations(page); + + const onMyPage = page.getByRole('button', { name: 'Vil prøve Rødvin 2' }); + await onMyPage.focus(); + 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.getByText(/Du har ikke lagret noen viner ennå/)).toBeVisible(); + }); + + test('«Har prøvd» på vinsiden tar vinen av «Vil prøve»', async ({ page }) => { + await fakeApi(page); + await page.goto('./vin/1'); + await loggedIn(page); + // exact: «Lignende viner» has cards with buttons like «Vil prøve Rødvin 2». + const wantToTry = page.getByRole('button', { name: 'Vil prøve', exact: true }); + const tried = page.getByRole('button', { name: 'Har prøvd', exact: true }); + + await wantToTry.click(); + await expect(wantToTry).toHaveAttribute('aria-pressed', 'true'); + await tried.click(); + + await expect(tried).toHaveAttribute('aria-pressed', 'true'); + await expect(wantToTry).toHaveAttribute('aria-pressed', 'false'); + await page.goto('./mine'); + await expect(page.getByText(/Du har ikke lagret noen viner ennå/)).toBeVisible(); + }); + + test('en besøkende logger inn og kommer tilbake til søket', async ({ page }) => { + await fakeApi(page, { loggedIn: false }); + await page.goto('./sok?q=rod'); + + await page.getByRole('button', { name: 'Favoritt Rødvin 1' }).click(); + await expect(page).toHaveURL(/\/konto$/); + 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(); + + await expect(page).toHaveURL(/\/sok\?q=rod$/); + await expect(page.getByRole('button', { name: 'Favoritt Rødvin 1' })).toBeVisible(); + }); + + test('en «Vil prøve»-liste fra før innlogging flyttes til brukeren, én gang', async ({ + page, + }) => { + // The old list, oldest first, as the site stored it before login. Only on the first page + // load: an init script runs again on every load, and would put the list back. + await page.addInitScript(() => { + if (sessionStorage.getItem('seeded')) return; + sessionStorage.setItem('seeded', 'yes'); + localStorage.setItem('kk:wishlist', JSON.stringify(['2', '1'])); + }); + await fakeApi(page); + await page.goto('./mine'); + + await expect(myList(page).getByRole('link')).toHaveText(['Rødvin 1', 'Rødvin 2']); + await expect.poll(() => page.evaluate(() => localStorage.getItem('kk:wishlist'))).toBeNull(); + + // A new page load imports nothing more: the list is the same. + await page.reload(); + 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 }) => { + await fakeApi(page); + await page.goto('./mine'); + await expect(page.getByText(/Du har ikke lagret noen viner ennå/)).toBeVisible(); + await expectNoAxeViolations(page); + }); +}); diff --git a/frontend/e2e/screenreader.spec.ts b/frontend/e2e/screenreader.spec.ts index 39d59ae..59a7292 100644 --- a/frontend/e2e/screenreader.spec.ts +++ b/frontend/e2e/screenreader.spec.ts @@ -22,6 +22,7 @@ const wine = (id: number, type: string) => ({ wineryName: 'Testprodusent', communityRating: 4, communityRatingCount: 10, + myLists: [], }); function winesResponse({ filter }: Variables, search?: string) { @@ -143,7 +144,8 @@ test.describe('Skjermleser og fokus', () => { for (const [name, path, title] of [ ['innlogging', './konto', 'Logg inn'], - ['Mine anmeldelser uten lagrede viner', './mine', 'Mine anmeldelser'], + // Behind login: a visitor is sent to /konto. The page itself is tested in lists.spec.ts. + ['Mine anmeldelser for en besøkende', './mine', 'Logg inn'], ['søk uten treff', './sok?q=finnesikke', 'Utforsk viner'], ['siden som ikke finnes', './finnesikke', 'Fant ikke siden'], ]) { diff --git a/frontend/e2e/search.spec.ts b/frontend/e2e/search.spec.ts index f586fd2..06ae251 100644 --- a/frontend/e2e/search.spec.ts +++ b/frontend/e2e/search.spec.ts @@ -23,6 +23,7 @@ const wine = (id: number) => ({ wineryName: 'Testprodusent', communityRating: 4.5, communityRatingCount: 10, + myLists: [], }); function winesResponse({ search, after, first = 24 }: Variables) { diff --git a/frontend/e2e/wine.spec.ts b/frontend/e2e/wine.spec.ts index f487d00..f45ea04 100644 --- a/frontend/e2e/wine.spec.ts +++ b/frontend/e2e/wine.spec.ts @@ -1,6 +1,6 @@ import AxeBuilder from '@axe-core/playwright'; import { expect, test, type Page } from '@playwright/test'; -import { stubGraphQL } from './support/graphql'; +import { stubGraphQL, type Handler } from './support/graphql'; /* E2E for the detail page. Runs against `vite preview` with a stubbed GraphQL API. */ const wine = { @@ -22,6 +22,7 @@ const wine = { vintages: [2020, 2005], communityRating: 4.12, communityRatingCount: 12, + myLists: [], }; const searchResult = { @@ -35,7 +36,11 @@ const searchResult = { }, }; -async function stubApi(page: Page) { +/** A logged-in user, for the tests of the list buttons. */ +const KARI = { __typename: 'User', id: '1', username: 'kari', createdAt: '2026-11-19T12:00:00Z' }; + +/** `overrides` replaces or adds handlers, for example `Me` for a logged-in user. */ +async function stubApi(page: Page, overrides: Record = {}) { await stubGraphQL(page, { Wine: (variables: { id?: string }) => ({ data: { wine: variables.id === wine.id ? wine : null }, @@ -54,6 +59,7 @@ async function stubApi(page: Page) { }), // Both the search page and «Lignende viner» on the wine page use SearchWines. SearchWines: () => searchResult, + ...overrides, }); } @@ -97,16 +103,56 @@ test.describe('Detaljsiden', () => { await expect(page).toHaveURL(/\/sok\?mat=Beef$/); }); - test('husker «Vil prøve» etter omlasting', async ({ page }) => { + test('en besøkende som vil lagre vinen, sendes til innlogging', async ({ page }) => { await stubApi(page); await page.goto('./vin/100062'); - const button = page.getByRole('button', { name: 'Vil prøve' }); - await button.click(); - await expect(button).toHaveAttribute('aria-pressed', 'true'); + await page.getByRole('button', { name: 'Vil prøve' }).click(); + + await expect(page).toHaveURL(/\/konto$/); + }); + + test('listene ligger på serveren, så de er der etter omlasting', async ({ page }) => { + // A small fake server: it remembers the lists between requests, like the real API. + let myLists: string[] = []; + await stubApi(page, { + Me: () => ({ data: { me: KARI } }), + // Both queries that return this wine must give the same lists, like the real API does. + // The cache keeps one copy of the wine, and the answer that comes last decides. + Wine: () => ({ data: { wine: { ...wine, myLists } } }), + SearchWines: () => ({ + data: { + wines: { + ...searchResult.data.wines, + edges: [{ __typename: 'WineEdge', cursor: '1', node: { ...wine, myLists } }], + }, + }, + }), + SetWineInList: (variables: { list: string; inList: boolean }) => { + myLists = variables.inList + ? [...myLists, variables.list] + : myLists.filter((list) => list !== variables.list); + return { data: { setWineInList: { __typename: 'Wine', id: wine.id, myLists } } }; + }, + }); + await page.goto('./vin/100062'); + // The header shows the username once the page knows who is logged in. A click before + // that is ignored on purpose, so the test waits for it. + await expect(page.getByRole('link', { name: 'kari' })).toBeAttached(); + const favourite = page.getByRole('button', { name: 'Favoritt' }); + + // With the keyboard: focus the button and press Space. + await favourite.focus(); + await page.keyboard.press('Space'); + await expect(favourite).toHaveAttribute('aria-pressed', 'true'); + await expect.poll(() => myLists).toEqual(['FAVOURITE']); + await page.reload(); - await expect(button).toHaveAttribute('aria-pressed', 'true'); + await expect(page.getByRole('button', { name: 'Favoritt' })).toHaveAttribute( + 'aria-pressed', + 'true', + ); }); test('forklarer når vinen ikke finnes', async ({ page }) => { diff --git a/frontend/src/app/App.test.tsx b/frontend/src/app/App.test.tsx index c9daa16..dbb4510 100644 --- a/frontend/src/app/App.test.tsx +++ b/frontend/src/app/App.test.tsx @@ -34,7 +34,8 @@ describe('AppRoutes', () => { it.each([ ['/finnes-ikke', 'Fant ikke siden'], ['/vin/abc', 'Fant ikke vinen'], - ['/mine', 'Mine anmeldelser'], + // Behind login: a visitor is sent to /konto. + ['/mine', '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 0baa349..ea5ca11 100644 --- a/frontend/src/app/App.tsx +++ b/frontend/src/app/App.tsx @@ -1,6 +1,7 @@ import { lazy } from 'react'; import { BrowserRouter, Route, Routes } from 'react-router'; import { AppLayout } from '../components/layout/AppLayout'; +import { RequireAuth } from '../features/auth/RequireAuth'; import NotFoundPage from './NotFoundPage'; // Kodesplitting per rute: forsiden laster ikke koden for søk og detaljside. @@ -20,7 +21,15 @@ export function AppRoutes() { } /> } /> } /> - } /> + {/* The lists belong to a user, so the page asks visitors to log in and sends them back. */} + + + + } + /> } /> } /> diff --git a/frontend/src/components/layout/AppLayout.tsx b/frontend/src/components/layout/AppLayout.tsx index 0c94d9c..a9747b8 100644 --- a/frontend/src/components/layout/AppLayout.tsx +++ b/frontend/src/components/layout/AppLayout.tsx @@ -5,6 +5,7 @@ import { Footer } from './Footer'; import { Header } from './Header'; import { focusHeadingWhenReady } from '../../lib/focus'; import { RouteErrorBoundary } from './RouteErrorBoundary'; +import { useLegacyWishlistImport } from '../../features/lists/useLegacyWishlistImport'; import styles from './AppLayout.module.css'; /** @@ -14,6 +15,8 @@ import styles from './AppLayout.module.css'; */ export function AppLayout() { const { pathname } = useLocation(); + // A «Vil prøve» list from before login moves to the user once, whichever page they log in on. + useLegacyWishlistImport(); // Compared with the previous path instead of counting renders. StrictMode runs effects // twice in development, and a counter would then move focus on the very first load. const previousPathname = useRef(pathname); diff --git a/frontend/src/components/ui/BookmarkIcon.tsx b/frontend/src/components/ui/BookmarkIcon.tsx new file mode 100644 index 0000000..9c01bfc --- /dev/null +++ b/frontend/src/components/ui/BookmarkIcon.tsx @@ -0,0 +1,8 @@ +/** The bookmark on the «Vil prøve» buttons. Decorative: the button has its own text or label. */ +export function BookmarkIcon() { + return ( + + ); +} diff --git a/frontend/src/components/ui/CheckIcon.tsx b/frontend/src/components/ui/CheckIcon.tsx new file mode 100644 index 0000000..2fd50ab --- /dev/null +++ b/frontend/src/components/ui/CheckIcon.tsx @@ -0,0 +1,9 @@ +/** The check mark on the «Har prøvd» buttons. Decorative: the button has its own text or label. */ +export function CheckIcon() { + return ( + + ); +} diff --git a/frontend/src/components/ui/HeartIcon.tsx b/frontend/src/components/ui/HeartIcon.tsx index ad37ca3..612c2fd 100644 --- a/frontend/src/components/ui/HeartIcon.tsx +++ b/frontend/src/components/ui/HeartIcon.tsx @@ -1,4 +1,4 @@ -/** The heart on the "Vil prøve" buttons. Decorative: the button has its own text or label. */ +/** The heart on the favourite buttons. Decorative: the button has its own text or label. */ export function HeartIcon() { return (
+ {ON_CARD.map((list) => { + const { label, Icon } = LIST_BUTTONS[list]; + const { isSaved, toggle } = states[list]; + return ( + + ); + })} +
+ {/* Only in the DOM after a failure: an element with role="alert" is read when it appears. */} + {error && ( +

+ {error} +

+ )} + + ); +} diff --git a/frontend/src/features/lists/components/WineListButtons.module.css b/frontend/src/features/lists/components/WineListButtons.module.css new file mode 100644 index 0000000..0a02eab --- /dev/null +++ b/frontend/src/features/lists/components/WineListButtons.module.css @@ -0,0 +1,73 @@ +.wrapper { + display: grid; + gap: var(--space-2); +} + +.group { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.button { + display: inline-flex; + align-items: center; + gap: var(--space-2); + 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; +} + +.button:hover { + background: var(--color-surface-muted); +} + +.button svg { + width: 1.25rem; + height: 1.25rem; + fill: none; + stroke: var(--color-brand); + stroke-width: 2; + stroke-linecap: round; + stroke-linejoin: round; +} + +/* Pressed: the icon is filled, and the button gets a background, so the state does not rest on colour alone. */ +.button[aria-pressed='true'] { + background: var(--color-surface-muted); +} + +.button[aria-pressed='true'] svg { + fill: var(--color-brand); +} + +/* The check mark is drawn on top of the filled circle, so it needs its own colour. */ +.button[aria-pressed='true'] svg circle + path { + stroke: var(--color-surface); +} + +.hint { + font-size: var(--text-sm); + color: var(--color-text-muted); +} + +.error { + flex-basis: 100%; + font-size: var(--text-sm); + color: var(--color-danger); +} + +@media (prefers-color-scheme: dark) { + .button svg { + stroke: var(--cork-300); + } + + .button[aria-pressed='true'] svg { + fill: var(--cork-300); + } +} diff --git a/frontend/src/features/lists/components/WineListButtons.test.tsx b/frontend/src/features/lists/components/WineListButtons.test.tsx new file mode 100644 index 0000000..a95601c --- /dev/null +++ b/frontend/src/features/lists/components/WineListButtons.test.tsx @@ -0,0 +1,117 @@ +import { describe, expect, it } from 'vitest'; +import { render, screen, waitFor } 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 type { WineListName } from '../../../lib/wineLists'; +import { LocationProbe } from '../../../test/LocationProbe'; +import { ME_QUERY } from '../../auth/api/authQueries'; +import { AuthProvider } from '../../auth/AuthProvider'; +import { SET_WINE_IN_LIST_MUTATION, WINE_LISTS_FRAGMENT } from '../api/listQueries'; +import { WineListButtons } from './WineListButtons'; + +const WINE_ID = '100062'; +const USER = { __typename: 'User', id: '1', username: 'kari', createdAt: '2026-11-19T12:00:00Z' }; + +const me = (user: typeof USER | null): MockLink.MockedResponse => ({ + request: { query: ME_QUERY }, + result: { data: { me: user } }, +}); + +const setWineInList = ( + list: WineListName, + inList: boolean, + myLists: WineListName[], +): MockLink.MockedResponse => ({ + request: { query: SET_WINE_IN_LIST_MUTATION, variables: { wineId: WINE_ID, list, inList } }, + result: { data: { setWineInList: { __typename: 'Wine', id: WINE_ID, myLists } } }, +}); + +function renderButtons( + mocks: MockLink.MockedResponse[], + { loggedIn = true, lists = [] as WineListName[] } = {}, +) { + const cache = createApolloCache(); + cache.writeFragment({ + fragment: WINE_LISTS_FRAGMENT, + data: { __typename: 'Wine', id: WINE_ID, myLists: lists }, + }); + const user = userEvent.setup(); + const result = render( + + + + + } /> + Logg inn} /> + + + + + , + ); + return { user, ...result }; +} + +const button = (name: string) => screen.getByRole('button', { name }); + +describe('WineListButtons', () => { + it('shows three toggle buttons with visible names, in one named group', async () => { + renderButtons([], { lists: ['FAVOURITE', 'TRIED'] }); + + const group = await screen.findByRole('group', { name: 'Lagre vinen i listene dine' }); + expect(group).toContainElement(button('Favoritt')); + // Pressed once AuthProvider knows Kari is logged in. + await waitFor(() => expect(button('Favoritt')).toHaveAttribute('aria-pressed', 'true')); + expect(button('Vil prøve')).toHaveAttribute('aria-pressed', 'false'); + expect(button('Har prøvd')).toHaveAttribute('aria-pressed', 'true'); + }); + + it('can be used with the keyboard: Tab to a button, then Space or Enter', async () => { + const { user } = renderButtons( + [ + setWineInList('FAVOURITE', true, ['FAVOURITE', 'TRIED']), + setWineInList('WANT_TO_TRY', true, ['FAVOURITE', 'WANT_TO_TRY', 'TRIED']), + ], + { lists: ['TRIED'] }, + ); + // A click before AuthProvider knows who is logged in is ignored, so wait until it does. + await waitFor(() => expect(button('Har prøvd')).toHaveAttribute('aria-pressed', 'true')); + + await user.tab(); + expect(button('Favoritt')).toHaveFocus(); + await user.keyboard(' '); + expect(button('Favoritt')).toHaveAttribute('aria-pressed', 'true'); + + await user.tab(); + expect(button('Vil prøve')).toHaveFocus(); + await user.keyboard('{Enter}'); + expect(button('Vil prøve')).toHaveAttribute('aria-pressed', 'true'); + }); + + it('asks a visitor to log in, and sends them to /konto on a click', async () => { + const { user } = renderButtons([], { loggedIn: false }); + + expect( + await screen.findByText('Logg inn for å lagre vinen. Du kommer tilbake hit etterpå.'), + ).toBeInTheDocument(); + await user.click(button('Favoritt')); + + expect(await screen.findByRole('heading', { name: 'Logg inn' })).toBeInTheDocument(); + expect(screen.getByTestId('location')).toHaveTextContent('/konto'); + }); + + it('has no axe violations, for a user and for a visitor', async () => { + const { container, unmount } = renderButtons([], { lists: ['WANT_TO_TRY'] }); + await waitFor(() => expect(button('Vil prøve')).toHaveAttribute('aria-pressed', 'true')); + expect(await axe(container)).toHaveNoViolations(); + unmount(); + + const visitor = renderButtons([], { loggedIn: false }); + await screen.findByText(/Logg inn for å lagre vinen/); + expect(await axe(visitor.container)).toHaveNoViolations(); + }); +}); diff --git a/frontend/src/features/lists/components/WineListButtons.tsx b/frontend/src/features/lists/components/WineListButtons.tsx new file mode 100644 index 0000000..28802a2 --- /dev/null +++ b/frontend/src/features/lists/components/WineListButtons.tsx @@ -0,0 +1,54 @@ +import type { WineListName } from '../../../lib/wineLists'; +import { useAuth } from '../../auth/useAuth'; +import { useWineList } from '../useWineList'; +import { LIST_BUTTONS } from './listButtons'; +import styles from './WineListButtons.module.css'; + +const ORDER: WineListName[] = ['FAVOURITE', 'WANT_TO_TRY', 'TRIED']; + +interface WineListButtonsProps { + wineId: string; +} + +/** + * The three list buttons on the wine page: «Favoritt», «Vil prøve» and «Har prøvd». + * Each is a toggle button (aria-pressed) with a visible name, so screen readers say + * «Favoritt, toggle button, pressed» and voice control can use the word on the button. + */ +export function WineListButtons({ wineId }: WineListButtonsProps) { + const { user, loading } = useAuth(); + + return ( +
+ {/* role="group" with a name tells screen readers that the three buttons belong together. */} +
+ {ORDER.map((list) => ( + + ))} +
+ {!loading && !user && ( +

Logg inn for å lagre vinen. Du kommer tilbake hit etterpå.

+ )} +
+ ); +} + +function ListButton({ wineId, list }: { wineId: string; list: WineListName }) { + const { isSaved, toggle, error } = useWineList(wineId, list); + const { label, Icon } = LIST_BUTTONS[list]; + + return ( + <> + + {/* Only in the DOM after a failure: an element with role="alert" is read when it appears. */} + {error && ( +

+ {error} +

+ )} + + ); +} diff --git a/frontend/src/features/lists/components/listButtons.ts b/frontend/src/features/lists/components/listButtons.ts new file mode 100644 index 0000000..0bc3732 --- /dev/null +++ b/frontend/src/features/lists/components/listButtons.ts @@ -0,0 +1,15 @@ +import type { ComponentType } from 'react'; +import { BookmarkIcon } from '../../../components/ui/BookmarkIcon'; +import { CheckIcon } from '../../../components/ui/CheckIcon'; +import { HeartIcon } from '../../../components/ui/HeartIcon'; +import type { WineListName } from '../../../lib/wineLists'; + +/** + * The text and icon of each list, the same everywhere in the app. In its own file, because a + * component file that also exports constants breaks fast refresh (react-refresh/only-export-components). + */ +export const LIST_BUTTONS: Record = { + FAVOURITE: { label: 'Favoritt', Icon: HeartIcon }, + WANT_TO_TRY: { label: 'Vil prøve', Icon: BookmarkIcon }, + TRIED: { label: 'Har prøvd', Icon: CheckIcon }, +}; diff --git a/frontend/src/features/lists/legacyWishlist.test.ts b/frontend/src/features/lists/legacyWishlist.test.ts new file mode 100644 index 0000000..6b6a309 --- /dev/null +++ b/frontend/src/features/lists/legacyWishlist.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest'; +import { ApolloClient, ApolloLink } from '@apollo/client'; +import { MockLink } from '@apollo/client/testing'; +import { createApolloCache } from '../../lib/apollo'; +import { SET_WINE_IN_LIST_MUTATION } from './api/listQueries'; +import { importLegacyWishlist, LEGACY_WISHLIST_KEY, readLegacyWishlist } from './legacyWishlist'; + +const store = (value: string) => window.localStorage.setItem(LEGACY_WISHLIST_KEY, value); +const stored = () => window.localStorage.getItem(LEGACY_WISHLIST_KEY); + +/** The API's answer when the wine is put on «Vil prøve»: an error, or the wine's lists. */ +function answer(wineId: string, outcome: 'ok' | 'gone' | 'offline'): MockLink.MockedResponse { + const request = { + query: SET_WINE_IN_LIST_MUTATION, + variables: { wineId, list: 'WANT_TO_TRY', inList: true }, + }; + if (outcome === 'offline') return { request, error: new TypeError('Failed to fetch') }; + if (outcome === 'gone') { + return { + request, + result: { + errors: [{ message: 'Wine not found.', extensions: { code: 'BAD_USER_INPUT' } }], + }, + }; + } + return { + request, + result: { + data: { setWineInList: { __typename: 'Wine', id: wineId, myLists: ['WANT_TO_TRY'] } }, + }, + }; +} + +/** A client against fake answers. `sent` gets the wine ids in the order they were sent. */ +function clientFor(mocks: MockLink.MockedResponse[]) { + const sent: string[] = []; + const recorder = new ApolloLink((operation, forward) => { + sent.push(operation.variables.wineId as string); + return forward(operation); + }); + const client = new ApolloClient({ + link: ApolloLink.from([recorder, new MockLink(mocks)]), + cache: createApolloCache(), + }); + return { client, sent }; +} + +describe('readLegacyWishlist', () => { + it('reads the wine ids in the stored order', () => { + store('["100062","111427"]'); + expect(readLegacyWishlist()).toEqual(['100062', '111427']); + }); + + it.each(['{not json', '{"1":true}', '[1, null, "abc", "1e9"]'])( + 'treats %s as an empty list', + (value) => { + store(value); + expect(readLegacyWishlist()).toEqual([]); + }, + ); +}); + +describe('importLegacyWishlist', () => { + it('puts the wines on «Vil prøve» oldest first, and then removes the old list', async () => { + store('["1","2"]'); + const { client, sent } = clientFor([answer('1', 'ok'), answer('2', 'ok')]); + + expect(await importLegacyWishlist(client, '9')).toEqual({ imported: 2, done: true }); + + expect(sent).toEqual(['1', '2']); + expect(stored()).toBeNull(); + }); + + it('skips a wine that is no longer in the catalogue', async () => { + store('["1","2"]'); + const { client } = clientFor([answer('1', 'gone'), answer('2', 'ok')]); + + expect(await importLegacyWishlist(client, '9')).toEqual({ imported: 1, done: true }); + expect(stored()).toBeNull(); + }); + + it('keeps the old list for the next login when the connection fails', async () => { + store('["1","2","3"]'); + const { client, sent } = clientFor([answer('1', 'ok'), answer('2', 'offline')]); + + expect(await importLegacyWishlist(client, '9')).toEqual({ imported: 1, done: false }); + + expect(sent).toEqual(['1', '2']); // Stops at the first failure. + expect(stored()).toBe('["1","2","3"]'); + }); + + it('sends nothing when there is no old list', async () => { + const { client, sent } = clientFor([]); + expect(await importLegacyWishlist(client, '9')).toEqual({ imported: 0, done: true }); + expect(sent).toEqual([]); + }); +}); diff --git a/frontend/src/features/lists/legacyWishlist.ts b/frontend/src/features/lists/legacyWishlist.ts new file mode 100644 index 0000000..af0dba3 --- /dev/null +++ b/frontend/src/features/lists/legacyWishlist.ts @@ -0,0 +1,71 @@ +import type { ApolloClient } from '@apollo/client'; +import { classifyError } from '../../lib/errors'; +import { updateListPages } from './api/listCache'; +import { + SET_WINE_IN_LIST_MUTATION, + type SetWineInListData, + type SetWineInListVariables, +} from './api/listQueries'; + +/** + * Before login, «Vil prøve» was kept in the browser under this key, oldest first. The list now + * lives on the user, and this file moves an old list there once, after the first login. + */ +export const LEGACY_WISHLIST_KEY = 'kk:wishlist'; + +/** The wine ids in the old list, oldest first. Anything that is not a list of ids counts as empty. */ +export function readLegacyWishlist(): string[] { + try { + const parsed: unknown = JSON.parse(window.localStorage.getItem(LEGACY_WISHLIST_KEY) ?? '[]'); + return Array.isArray(parsed) + ? parsed.filter((id): id is string => typeof id === 'string' && /^\d{1,9}$/.test(id)) + : []; + } catch { + // Broken JSON, or storage that is turned off (private mode in some browsers). + return []; + } +} + +function forgetLegacyWishlist() { + try { + window.localStorage.removeItem(LEGACY_WISHLIST_KEY); + } catch { + // Storage that is turned off has nothing to forget. + } +} + +/** How an import went: how many wines were added, and whether the old list is gone. */ +export interface ImportResult { + imported: number; + done: boolean; +} + +/** + * Puts the wines from the old list on the user's «Vil prøve», oldest first, so the newest ends up + * at the top as before. A wine that no longer exists is skipped. The old list is only removed + * when every wine has been handled; if the connection fails, the rest is tried after the next login. + */ +export async function importLegacyWishlist( + client: ApolloClient, + userId: string, +): Promise { + let imported = 0; + for (const wineId of readLegacyWishlist()) { + try { + await client.mutate({ + mutation: SET_WINE_IN_LIST_MUTATION, + variables: { wineId, list: 'WANT_TO_TRY', inList: true }, + update(cache, { data }) { + const after = data?.setWineInList.myLists; + if (after) updateListPages(cache, { userId, wineId, before: [], after }); + }, + }); + imported += 1; + } catch (error) { + // BAD_USER_INPUT: the wine is no longer in the catalogue. Anything else is worth another try. + if (classifyError(error) !== 'badInput') return { imported, done: false }; + } + } + forgetLegacyWishlist(); + return { imported, done: true }; +} diff --git a/frontend/src/features/lists/useLegacyWishlistImport.test.tsx b/frontend/src/features/lists/useLegacyWishlistImport.test.tsx new file mode 100644 index 0000000..c62a4a7 --- /dev/null +++ b/frontend/src/features/lists/useLegacyWishlistImport.test.tsx @@ -0,0 +1,62 @@ +import { describe, expect, it, vi } from 'vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import type { MockLink } from '@apollo/client/testing'; +import { MockedProvider } from '@apollo/client/testing/react'; +import { createApolloCache } from '../../lib/apollo'; +import { meMock, TEST_USER } from '../../test/authMocks'; +import { AuthReady } from '../../test/AuthReady'; +import { AuthProvider } from '../auth/AuthProvider'; +import { SET_WINE_IN_LIST_MUTATION } from './api/listQueries'; +import { LEGACY_WISHLIST_KEY } from './legacyWishlist'; +import { useLegacyWishlistImport } from './useLegacyWishlistImport'; + +function Importer() { + useLegacyWishlistImport(); + return null; +} + +function setup(user: typeof TEST_USER | null) { + const sent = vi.fn(); + const mock: MockLink.MockedResponse = { + request: { + query: SET_WINE_IN_LIST_MUTATION, + variables: { wineId: '100062', list: 'WANT_TO_TRY', inList: true }, + }, + result: () => { + sent(); + return { + data: { setWineInList: { __typename: 'Wine', id: '100062', myLists: ['WANT_TO_TRY'] } }, + }; + }, + maxUsageCount: 2, // So a second import would be seen, not refused. + }; + render( + + + + + + + , + ); + return { sent }; +} + +describe('useLegacyWishlistImport', () => { + it('moves the old list to the logged-in user once, also when used twice', async () => { + window.localStorage.setItem(LEGACY_WISHLIST_KEY, '["100062"]'); + const { sent } = setup(TEST_USER); + + await waitFor(() => expect(window.localStorage.getItem(LEGACY_WISHLIST_KEY)).toBeNull()); + expect(sent).toHaveBeenCalledOnce(); + }); + + it('leaves the old list alone for a visitor', async () => { + window.localStorage.setItem(LEGACY_WISHLIST_KEY, '["100062"]'); + const { sent } = setup(null); + + await screen.findByTestId('auth-ready'); + expect(window.localStorage.getItem(LEGACY_WISHLIST_KEY)).toBe('["100062"]'); + expect(sent).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/features/lists/useLegacyWishlistImport.ts b/frontend/src/features/lists/useLegacyWishlistImport.ts new file mode 100644 index 0000000..b1d30d2 --- /dev/null +++ b/frontend/src/features/lists/useLegacyWishlistImport.ts @@ -0,0 +1,28 @@ +import { useEffect } from 'react'; +import { useApolloClient } from '@apollo/client/react'; +import { useAuth } from '../auth/useAuth'; +import { importLegacyWishlist, readLegacyWishlist } from './legacyWishlist'; + +/** + * One import at a time for the whole app. StrictMode runs effects twice in development, and two + * imports at once would send every wine twice. + */ +let running: Promise | null = null; + +/** + * Moves a «Vil prøve» list from before login (kept in this browser) to the user who logs in, + * once. Also for a user who was already logged in when this version of the site came out. + * Used once, in the layout around every page. + */ +export function useLegacyWishlistImport() { + const { user } = useAuth(); + const client = useApolloClient(); + const userId = user?.id; + + useEffect(() => { + if (!userId || running || readLegacyWishlist().length === 0) return; + running = importLegacyWishlist(client, userId).finally(() => { + running = null; + }); + }, [client, userId]); +} diff --git a/frontend/src/features/lists/useWineList.test.tsx b/frontend/src/features/lists/useWineList.test.tsx new file mode 100644 index 0000000..7be5e38 --- /dev/null +++ b/frontend/src/features/lists/useWineList.test.tsx @@ -0,0 +1,234 @@ +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 { MemoryRouter, Route, Routes, useLocation } from 'react-router'; +import { createApolloCache } from '../../lib/apollo'; +import type { WineListName } from '../../lib/wineLists'; +import { ME_QUERY } from '../auth/api/authQueries'; +import { AuthProvider } from '../auth/AuthProvider'; +import { useAuth } from '../auth/useAuth'; +import { SET_WINE_IN_LIST_MUTATION, WINE_LISTS_FRAGMENT } from './api/listQueries'; +import { useWineList } from './useWineList'; + +const WINE_ID = '7'; +const USER = { __typename: 'User', id: '1', username: 'kari', createdAt: '2026-11-19T12:00:00Z' }; + +/** A plain button for one list, as the real buttons use the hook. */ +function ListButton({ list }: { list: WineListName }) { + const { isSaved, toggle, error } = useWineList(WINE_ID, list); + return ( + <> + + {error &&

{error}

} + + ); +} + +/** Shown once AuthProvider knows who is logged in. Before that, a click is ignored on purpose. */ +function Ready() { + const { loading } = useAuth(); + return loading ? null :

Klar

; +} + +/** Shows where a visitor was sent, and the page they will come back to. */ +function LoginPage() { + const state = useLocation().state as { from?: string } | null; + return

Logg inn, så tilbake til {state?.from}

; +} + +const me = (user: typeof USER | null): MockLink.MockedResponse => ({ + request: { query: ME_QUERY }, + result: { data: { me: user } }, +}); + +function setWineInList( + list: WineListName, + inList: boolean, + answer: MockLink.MockedResponse['result'] | Error, + delay?: number, +): MockLink.MockedResponse { + const request = { + query: SET_WINE_IN_LIST_MUTATION, + variables: { wineId: WINE_ID, list, inList }, + }; + return answer instanceof Error + ? { request, error: answer, delay } + : { request, result: answer, delay }; +} + +const wineWith = (myLists: WineListName[]) => ({ + data: { setWineInList: { __typename: 'Wine', id: WINE_ID, myLists } }, +}); + +/** 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[] } = {}, +) { + const cache = createApolloCache(); + cache.writeFragment({ + fragment: WINE_LISTS_FRAGMENT, + data: { __typename: 'Wine', id: WINE_ID, myLists: lists }, + }); + const user = userEvent.setup(); + render( + + + + + + + + + + + } + /> + } /> + + + + , + ); + return { user, cache }; +} + +const button = (list: WineListName) => screen.getByRole('button', { name: list }); + +const ready = () => screen.findByText('Klar'); + +describe('useWineList', () => { + it('shows the lists the wine is on, from the cache', async () => { + renderButtons([], { lists: ['FAVOURITE'] }); + await ready(); + expect(button('FAVOURITE')).toHaveAttribute('aria-pressed', 'true'); + expect(button('WANT_TO_TRY')).toHaveAttribute('aria-pressed', 'false'); + expect(button('TRIED')).toHaveAttribute('aria-pressed', 'false'); + }); + + 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)], + { lists: ['FAVOURITE'] }, + ); + await ready(); + + await user.click(button('WANT_TO_TRY')); + + expect(button('WANT_TO_TRY')).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']))], + { lists: ['FAVOURITE', 'WANT_TO_TRY'] }, + ); + await ready(); + + await user.click(button('TRIED')); + + expect(button('TRIED')).toHaveAttribute('aria-pressed', 'true'); + expect(button('WANT_TO_TRY')).toHaveAttribute('aria-pressed', 'false'); + }); + + it('takes the wine off the list, and keeps the answer from the API', async () => { + const { user } = renderButtons([setWineInList('FAVOURITE', false, wineWith([]))], { + lists: ['FAVOURITE'], + }); + await ready(); + + await user.click(button('FAVOURITE')); + + await waitFor(() => expect(button('FAVOURITE')).toHaveAttribute('aria-pressed', 'false')); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + }); + + it('goes back and says why when the change fails', async () => { + const { user } = renderButtons( + [setWineInList('TRIED', true, new TypeError('Failed to fetch'))], + { lists: ['FAVOURITE', 'WANT_TO_TRY'] }, + ); + await ready(); + + await user.click(button('TRIED')); + + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Vi fikk ikke lagret endringen. Vi fikk ikke kontakt med serveren.', + ); + expect(button('TRIED')).toHaveAttribute('aria-pressed', 'false'); + expect(button('WANT_TO_TRY')).toHaveAttribute('aria-pressed', 'true'); + }); + + it('takes the wine off the user’s list pages in the cache at once', async () => { + const { user, cache } = renderButtons([setWineInList('FAVOURITE', false, wineWith([]))], { + lists: ['FAVOURITE'], + }); + const LIST = gql` + query MyList { + me { + id + wines(list: FAVOURITE) { + totalCount + edges { + cursor + node { + id + } + } + } + } + } + `; + cache.writeQuery({ + query: LIST, + data: { + me: { + __typename: 'User', + id: USER.id, + wines: { + __typename: 'WineConnection', + totalCount: 1, + edges: [ + { __typename: 'WineEdge', cursor: 'c', node: { __typename: 'Wine', id: WINE_ID } }, + ], + }, + }, + }, + }); + await ready(); + + await user.click(button('FAVOURITE')); + + // At once in the optimistic layer, which the page reads ... + expect(cache.readQuery({ query: LIST, optimistic: true })).toMatchObject({ + me: { wines: { totalCount: 0, edges: [] } }, + }); + // ... and for good when the API has answered. + await waitFor(() => + expect(cache.readQuery({ query: LIST })).toMatchObject({ + me: { wines: { totalCount: 0, edges: [] } }, + }), + ); + }); + + it('sends a visitor to log in, and back to the same page afterwards', async () => { + const { user } = renderButtons([], { loggedIn: false, lists: ['FAVOURITE'] }); + await ready(); + // A visitor has no lists, even if the cache still has some from before. + expect(button('FAVOURITE')).toHaveAttribute('aria-pressed', 'false'); + + await user.click(button('WANT_TO_TRY')); + + expect( + await screen.findByText(`Logg inn, så tilbake til /vin/${WINE_ID}?fra=sok`), + ).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/features/lists/useWineList.ts b/frontend/src/features/lists/useWineList.ts new file mode 100644 index 0000000..665209b --- /dev/null +++ b/frontend/src/features/lists/useWineList.ts @@ -0,0 +1,88 @@ +import { useRef, useState } from 'react'; +import { 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'; +import { useAuth } from '../auth/useAuth'; +import { updateListPages } from './api/listCache'; +import { + SET_WINE_IN_LIST_MUTATION, + WINE_LISTS_FRAGMENT, + type SetWineInListData, + type SetWineInListVariables, + type WineListsFragment, +} from './api/listQueries'; + +export interface WineListState { + /** True when the logged-in user has the wine on the list. Always false when logged out. */ + isSaved: boolean; + /** Puts the wine on the list or takes it off. Sends a visitor to /konto, and back afterwards. */ + toggle: () => void; + /** A Norwegian message when the last change failed. The button has then gone back. */ + error: string | null; +} + +/** + * Whether a wine is on one of the user's lists, and a function to change it. + * + * The button changes at once: the answer is written to the cache before the API has replied + * (optimisticResponse), with the same rules as the API, and Apollo puts it back if the request + * fails. Every button for the same wine reads the same object in the cache, so a heart on the + * landing page and on the wine page always agree. + */ +export function useWineList(wineId: string, list: WineListName): WineListState { + const { user, loading: checkingLogin } = useAuth(); + 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, + ); + + const { data } = useFragment({ + fragment: WINE_LISTS_FRAGMENT, + from: { __typename: 'Wine', id: wineId }, + }); + // A wine fetched without `myLists` (or not yet fetched) is on no list as far as we know. + const lists = (data?.myLists ?? []).filter((name): name is WineListName => Boolean(name)); + const isSaved = Boolean(user) && lists.includes(list); + + async function change() { + // Until we know who is logged in, a click could go either way. + if (checkingLogin || pending.current) return; + if (!user) { + await navigate('/konto', { state: { from: location.pathname + location.search } }); + return; + } + + const inList = !isSaved; + pending.current = true; + setError(null); + try { + await setWineInList({ + variables: { wineId, list, inList }, + optimisticResponse: { + setWineInList: { + __typename: 'Wine', + id: wineId, + myLists: listsAfterChange(lists, list, inList), + }, + }, + // Also runs for the optimistic answer, so pages that list the user's wines change at once. + update(cache, { data: answer }) { + const after = answer?.setWineInList.myLists; + if (after) updateListPages(cache, { userId: user.id, wineId, before: lists, after }); + }, + }); + } catch (failure) { + setError(`Vi fikk ikke lagret endringen. ${ERROR_DETAILS[classifyError(failure)]}`); + } finally { + pending.current = false; + } + } + + return { isSaved, toggle: () => void change(), error }; +} diff --git a/frontend/src/features/my/MyPage.test.tsx b/frontend/src/features/my/MyPage.test.tsx index b4eb6ee..c15addf 100644 --- a/frontend/src/features/my/MyPage.test.tsx +++ b/frontend/src/features/my/MyPage.test.tsx @@ -1,91 +1,130 @@ -import { afterEach, describe, expect, it } from 'vitest'; -import { render, screen, within } from '@testing-library/react'; +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 } 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 { 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 MyPage from './MyPage'; -import { wishlistQuery, wishlistVariables } from './api/wishlistQuery'; -const WISHLIST_KEY = 'kk:wishlist'; - -const apiWine = (id: string, name: string, type = 'Red') => ({ +const apiWine = (id: string, name: string) => ({ __typename: 'Wine', id, name, - type, + type: 'Red', grapes: ['Merlot'], country: 'Italy', countryCode: 'IT', wineryName: 'Produsent', communityRating: 4.2, communityRatingCount: 12, + myLists: ['WANT_TO_TRY'], }); -/** One answer for the wines on the list, in the order the page asks for them. */ -function wines(saved: { id: string; name: string }[]): MockLink.MockedResponse { - const ids = saved.map((wine) => wine.id); +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: wishlistQuery(ids), variables: wishlistVariables(ids) }, + request: { + query: MY_WINE_LIST_QUERY, + variables: { list: 'WANT_TO_TRY', first: LIST_PAGE_SIZE, ...(after ? { after } : {}) }, + }, result: { - data: Object.fromEntries( - saved.map((wine, index) => [`wine${index}`, apiWine(wine.id, wine.name)]), - ), + 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, + }, + }, + }, + }, }, }; } -/** The hearts are stored newest last, and the page shows them newest first. */ -function save(ids: string[]) { - window.localStorage.setItem(WISHLIST_KEY, JSON.stringify(ids)); -} - function renderPage(mocks: MockLink.MockedResponse[]) { const user = userEvent.setup(); const result = render( - - - + + + + + + , ); return { user, ...result }; } -afterEach(() => window.localStorage.clear()); +const list = () => screen.findByRole('list', { name: 'Viner du vil prøve' }); +const names = (element: HTMLElement) => + within(element) + .getAllByRole('link') + .map((link) => link.textContent); describe('MyPage', () => { - it('explains the empty list and links to the search', () => { - renderPage([]); - expect(screen.getByText(/Du har ikke lagret noen viner ennå/)).toBeInTheDocument(); + 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('Mine anmeldelser – Kork & Krone'); }); - it('shows the saved wines, newest first', async () => { - save(['100062', '111427']); + it('shows the wines on «Vil prøve» from the API, newest first', async () => { renderPage([ - wines([ + page([ { id: '111427', name: 'Chianti' }, { id: '100062', name: 'Origem Merlot' }, ]), ]); - const list = await screen.findByRole('list', { name: 'Viner du vil prøve' }); - const names = within(list) - .getAllByRole('link') - .map((link) => link.textContent); - expect(names).toEqual(['Chianti', 'Origem Merlot']); + expect(names(await list())).toEqual(['Chianti', 'Origem Merlot']); expect(screen.getByText('2 viner')).toBeInTheDocument(); }); - it('removes a wine from the list when the heart is clicked again', async () => { - save(['100062']); - const { user } = renderPage([wines([{ id: '100062', name: 'Origem Merlot' }])]); + 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(await screen.findByRole('button', { name: 'Vil prøve Origem Merlot' })); + 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, @@ -94,13 +133,30 @@ describe('MyPage', () => { expect(screen.getByRole('heading', { level: 2, name: 'Vil prøve' })).toHaveFocus(); }); + 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 () => { - save(['100062']); renderPage([ { request: { - query: wishlistQuery(['100062']), - variables: wishlistVariables(['100062']), + query: MY_WINE_LIST_QUERY, + variables: { list: 'WANT_TO_TRY', first: LIST_PAGE_SIZE }, }, error: new Error('Nede'), }, @@ -111,9 +167,8 @@ describe('MyPage', () => { }); it('has no axe violations', async () => { - save(['100062']); - const { container } = renderPage([wines([{ id: '100062', name: 'Origem Merlot' }])]); - await screen.findByRole('list', { name: 'Viner du vil prøve' }); + const { container } = renderPage([page([{ id: '100062', name: 'Origem Merlot' }])]); + await list(); expect(await axe(container)).toHaveNoViolations(); }); }); diff --git a/frontend/src/features/my/MyPage.tsx b/frontend/src/features/my/MyPage.tsx index d921ff0..8db6181 100644 --- a/frontend/src/features/my/MyPage.tsx +++ b/frontend/src/features/my/MyPage.tsx @@ -1,10 +1,10 @@ import { useDocumentTitle } from '../../hooks/useDocumentTitle'; -import { useWishlistWines } from './api/useWishlistWines'; +import { useMyWineList } from '../lists/api/useMyWineList'; import { MyView } from './MyView'; -/** Route component for `/mine`. Connects the data source to the presentation. */ +/** Route component for `/mine`, behind RequireAuth. Connects the data source to the presentation. */ export default function MyPage() { useDocumentTitle('Mine anmeldelser'); - const result = useWishlistWines(); - return ; + const wantToTry = useMyWineList('WANT_TO_TRY'); + return ; } diff --git a/frontend/src/features/my/MyView.module.css b/frontend/src/features/my/MyView.module.css index dca751d..711ad97 100644 --- a/frontend/src/features/my/MyView.module.css +++ b/frontend/src/features/my/MyView.module.css @@ -13,3 +13,24 @@ margin-top: var(--space-2); 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/MyView.tsx b/frontend/src/features/my/MyView.tsx index 360906b..3f7fc41 100644 --- a/frontend/src/features/my/MyView.tsx +++ b/frontend/src/features/my/MyView.tsx @@ -4,35 +4,60 @@ import { ErrorNotice } from '../../components/ui/ErrorNotice'; import { Skeleton } from '../../components/ui/Skeleton'; import { WineList } from '../../components/ui/WineList'; import { focusIfLost } from '../../lib/focus'; -import { pluralize } from '../../lib/format'; +import { formatCount, pluralize } from '../../lib/format'; import { buildSearchUrl } from '../../lib/searchParams'; -import type { WishlistResult } from './api/useWishlistWines'; +import type { MyWineListResult } from '../lists/api/useMyWineList'; import styles from './MyView.module.css'; -/** Presentation of «Mine anmeldelser». The list lives in the browser until we have login. */ -export function MyView({ wines, savedCount, loading, error, refetch }: WishlistResult) { +interface MyViewProps { + wantToTry: MyWineListResult; +} + +/** Presentation of «Mine anmeldelser»: the «Vil prøve» list, stored on the user. */ +export function MyView({ wantToTry }: MyViewProps) { + const { wines, totalCount, loading, loadingMore, hasNextPage, error, loadMoreError } = wantToTry; const headingRef = useRef(null); - const [previousCount, setPreviousCount] = useState(savedCount); + const [previousCount, setPreviousCount] = useState(totalCount); const [message, setMessage] = useState(''); - // A wine removed with its heart disappears from the list, and the button with it. + // A wine taken off the list with its bookmark disappears, and the button with it. // Saying so in the live region tells screen reader users that the click worked. - if (savedCount !== previousCount) { - setPreviousCount(savedCount); + if (totalCount !== previousCount) { + setPreviousCount(totalCount); + const removed = + totalCount !== undefined && previousCount !== undefined && totalCount < previousCount; setMessage( - savedCount < previousCount - ? `Fjernet fra listen. ${savedCount === 0 ? 'Listen er tom.' : `${pluralize(savedCount, 'vin', 'viner')} igjen.`}` + removed + ? `Fjernet fra listen. ${totalCount === 0 ? 'Listen er tom.' : `${pluralize(totalCount, 'vin', 'viner')} igjen.`}` : '', ); } + // «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 wantToTry.loadMore(); + } + // The removed card had focus, so it moves to the heading of the list. - const countBefore = useRef(savedCount); + const countBefore = useRef(totalCount); useEffect(() => { - const removed = savedCount < countBefore.current; - countBefore.current = savedCount; - if (removed) focusIfLost(headingRef.current); - }, [savedCount]); + const before = countBefore.current; + countBefore.current = totalCount; + if (totalCount !== undefined && before !== undefined && totalCount < before) { + focusIfLost(headingRef.current); + } + }, [totalCount]); return (
@@ -44,37 +69,63 @@ export function MyView({ wines, savedCount, loading, error, refetch }: WishlistR

- {loading ? 'Laster viner …' : message} + {loading ? 'Laster viner …' : loadingMore ? 'Laster flere viner …' : message}

- {savedCount === 0 ? ( + {loading && } + + {error && !loading && wines.length === 0 && ( + + )} + + {totalCount === 0 && (

- Du har ikke lagret noen viner ennå. Trykk på hjertet på en vin for å legge den her.{' '} + Du har ikke lagret noen viner ennå. Trykk på bokmerket på en vin for å legge den her.{' '} Utforsk viner

- ) : ( - <> -

{pluralize(savedCount, 'vin', 'viner')}

+ )} - {loading && wines.length === 0 && } + {totalCount !== undefined && totalCount > 0 && ( + <> +

+ {wines.length < totalCount + ? `Viser ${formatCount(wines.length)} av ${pluralize(totalCount, 'vin', 'viner')}` + : pluralize(totalCount, 'vin', 'viner')} +

+ + + )} - {error && ( - - )} + {loadMoreError && ( + + )} - {wines.length > 0 && } - + {hasNextPage && !loadMoreError && ( +

+ +

)}

Mine dommer

- Dommene dine vises her når innlogging er på plass. Fram til da finner du dem på vinsiden. + Dommene dine kommer her snart. Fram til da finner du dem på siden til hver vin.

diff --git a/frontend/src/features/my/api/useWishlistWines.ts b/frontend/src/features/my/api/useWishlistWines.ts deleted file mode 100644 index 224c0bd..0000000 --- a/frontend/src/features/my/api/useWishlistWines.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { useMemo } from 'react'; -import { useQuery } from '@apollo/client/react'; -import { useWishlistIds } from '../../../hooks/useWishlist'; -import { toWineSummary } from '../../../lib/mapWine'; -import type { WineSummary } from '../../../lib/types'; -import { wishlistQuery, wishlistVariables, type WishlistData } from './wishlistQuery'; - -export interface WishlistResult { - wines: WineSummary[]; - /** How many wines are on the list, also before they are loaded. */ - savedCount: number; - loading: boolean; - error: Error | undefined; - refetch: () => void; -} - -/** The wines on the «Vil prøve» list, fetched in one request. */ -export function useWishlistWines(): WishlistResult { - const ids = useWishlistIds(); - // useWishlistIds gives a new array every render, so the query is rebuilt from the ids as text. - const key = ids.join(','); - - // A new query object on every render would make Apollo fetch again in a loop. - const query = useMemo(() => wishlistQuery(key ? key.split(',') : []), [key]); - - const { data, loading, error, refetch } = useQuery(query, { - variables: wishlistVariables(ids), - skip: ids.length === 0, - }); - - const wines = ids - .map((_, index) => data?.[`wine${index}`]) - .filter((wine) => wine != null) - .map(toWineSummary) - .filter((wine): wine is WineSummary => wine !== null); - - return { - wines, - savedCount: ids.length, - loading, - error, - refetch: () => void refetch().catch(() => undefined), - }; -} diff --git a/frontend/src/features/my/api/wishlistQuery.test.ts b/frontend/src/features/my/api/wishlistQuery.test.ts deleted file mode 100644 index 7256a4c..0000000 --- a/frontend/src/features/my/api/wishlistQuery.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { print } from 'graphql'; -import { wishlistQuery, wishlistVariables } from './wishlistQuery'; - -describe('wishlistQuery', () => { - it('asks for one field per wine, with its own variable', () => { - const query = print(wishlistQuery(['1', '2'])); - expect(query).toContain('query Wishlist($id0: ID!, $id1: ID!)'); - expect(query).toContain('wine0: wine(id: $id0)'); - expect(query).toContain('wine1: wine(id: $id1)'); - }); - - it('is still valid GraphQL with an empty list', () => { - expect(print(wishlistQuery([]))).toContain('query Wishlist'); - }); -}); - -describe('wishlistVariables', () => { - it('numbers the ids in the same order', () => { - expect(wishlistVariables(['100062', '111427'])).toEqual({ - id0: '100062', - id1: '111427', - }); - }); -}); diff --git a/frontend/src/features/my/api/wishlistQuery.ts b/frontend/src/features/my/api/wishlistQuery.ts deleted file mode 100644 index 6b44142..0000000 --- a/frontend/src/features/my/api/wishlistQuery.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { gql } from '@apollo/client'; -import type { ApiWine } from '../../../lib/mapWine'; - -export interface WishlistData { - /** One wine per id, in the same order. A wine that no longer exists is null. */ - [key: `wine${number}`]: ApiWine | null; -} - -/** - * The API has no "wines by id" query, so we ask for each wine as its own field in - * one request: wine0, wine1 and so on. One round trip, and the Apollo cache reuses - * wines the user has already seen. - */ -export function wishlistQuery(ids: string[]) { - // With an empty list the page asks for nothing, but the query still has to be valid GraphQL. - if (ids.length === 0) { - return gql` - query Wishlist { - __typename - } - `; - } - - const fields = ids - .map( - (_, index) => ` - wine${index}: wine(id: $id${index}) { - id - name - type - grapes - country - countryCode - wineryName - communityRating - communityRatingCount - }`, - ) - .join(''); - - const variables = ids.map((_, index) => `$id${index}: ID!`).join(', '); - - return gql` - query Wishlist(${variables}) { - ${fields} - } - `; -} - -/** { id0: "123", id1: "456", ... } as the query expects them. */ -export function wishlistVariables(ids: string[]): Record { - return Object.fromEntries(ids.map((id, index) => [`id${index}`, id])); -} diff --git a/frontend/src/features/search/SearchFilters.test.tsx b/frontend/src/features/search/SearchFilters.test.tsx index e581ec4..25581ef 100644 --- a/frontend/src/features/search/SearchFilters.test.tsx +++ b/frontend/src/features/search/SearchFilters.test.tsx @@ -6,6 +6,8 @@ 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 { AuthProvider } from '../auth/AuthProvider'; +import { meMock } from '../../test/authMocks'; import { LocationProbe } from '../../test/LocationProbe'; import { filterOptionsMock, searchMock } from '../../test/searchMocks'; import SearchPage from './SearchPage'; @@ -21,13 +23,16 @@ function setScreen(wide: boolean) { function renderPage(mocks: MockLink.MockedResponse[], route = '/sok') { const user = userEvent.setup(); const result = render( - + // The wine cards have list buttons, which need to know who is logged in. + - - } /> - Annen side

} /> -
- + + + } /> + Annen side

} /> +
+ +
, ); diff --git a/frontend/src/features/search/SearchPage.test.tsx b/frontend/src/features/search/SearchPage.test.tsx index fdc985d..02c4fbc 100644 --- a/frontend/src/features/search/SearchPage.test.tsx +++ b/frontend/src/features/search/SearchPage.test.tsx @@ -8,6 +8,8 @@ import { MockedProvider } from '@apollo/client/testing/react'; import { MemoryRouter, Route, Routes, useNavigate } from 'react-router'; import { axe } from 'vitest-axe'; import { createApolloCache } from '../../lib/apollo'; +import { AuthProvider } from '../auth/AuthProvider'; +import { meMock } from '../../test/authMocks'; import { LocationProbe } from '../../test/LocationProbe'; import { searchMock, type SentVariables } from '../../test/searchMocks'; import { SEARCH_WINES_QUERY } from './api/searchQuery'; @@ -32,14 +34,17 @@ function renderPage( ) { const user = userEvent.setup(userOptions); const result = render( - + // The wine cards have list buttons, which need to know who is logged in. + - - } /> - Annen side

} /> -
- - + + + } /> + Annen side

} /> +
+ + +
, ); diff --git a/frontend/src/features/search/api/searchQuery.ts b/frontend/src/features/search/api/searchQuery.ts index 7acc65d..cd32cd3 100644 --- a/frontend/src/features/search/api/searchQuery.ts +++ b/frontend/src/features/search/api/searchQuery.ts @@ -23,6 +23,7 @@ export const SEARCH_WINES_QUERY = gql` wineryName communityRating communityRatingCount + myLists } } pageInfo { diff --git a/frontend/src/features/wine/WinePage.test.tsx b/frontend/src/features/wine/WinePage.test.tsx index 627669b..db1b789 100644 --- a/frontend/src/features/wine/WinePage.test.tsx +++ b/frontend/src/features/wine/WinePage.test.tsx @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { render, screen, within } from '@testing-library/react'; +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'; @@ -33,6 +33,7 @@ const wine = { vintages: [2020, 2005], communityRating: 4.12, communityRatingCount: 1234, + myLists: [] as string[], }; const found = (result = wine): MockLink.MockedResponse => ({ @@ -71,6 +72,16 @@ const visitor = (): MockLink.MockedResponse => ({ result: { data: { me: null } }, }); +/** Kari is logged in. Comes before `visitor()` in the mocks, so it is the answer that is used. */ +const loggedIn = (): MockLink.MockedResponse => ({ + request: { query: ME_QUERY }, + result: { + data: { + me: { __typename: 'User', id: '1', username: 'kari', createdAt: '2026-11-19T12:00:00Z' }, + }, + }, +}); + /** The similar wines section asks for its own data. These tests are about the rest of the page. */ const noSimilar = (): MockLink.MockedResponse => ({ request: { @@ -198,13 +209,31 @@ describe('WinePage – innhold', () => { expect(screen.queryByRole('link', { name: /Nettsiden til/ })).not.toBeInTheDocument(); }); - it('«Vil prøve» er en toggle-knapp', async () => { + it('har knappene for listene, og sender en besøkende til innlogging', async () => { const { user } = renderPage([found()]); await heading(); - const button = screen.getByRole('button', { name: 'Vil prøve' }); - expect(button).toHaveAttribute('aria-pressed', 'false'); - await user.click(button); - expect(button).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByRole('group', { name: 'Lagre vinen i listene dine' })).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Vil prøve' })); + + expect(await screen.findByText('Annen side')).toBeInTheDocument(); + expect(screen.getByTestId('location')).toHaveTextContent('/konto'); + }); + + it('viser listene vinen står på for en innlogget bruker', async () => { + renderPage([loggedIn(), found({ ...wine, myLists: ['FAVOURITE'] })]); + await heading(); + + await waitFor(() => + expect(screen.getByRole('button', { name: 'Favoritt' })).toHaveAttribute( + 'aria-pressed', + 'true', + ), + ); + expect(screen.getByRole('button', { name: 'Vil prøve' })).toHaveAttribute( + 'aria-pressed', + 'false', + ); }); }); diff --git a/frontend/src/features/wine/WineView.module.css b/frontend/src/features/wine/WineView.module.css index d784185..69c8eb1 100644 --- a/frontend/src/features/wine/WineView.module.css +++ b/frontend/src/features/wine/WineView.module.css @@ -79,46 +79,6 @@ font-weight: 700; } -.save { - display: inline-flex; - align-items: center; - gap: var(--space-2); - min-height: var(--tap-target); - padding: 0 var(--space-5); - border: 2px solid var(--color-link); - border-radius: var(--radius-pill); - background: transparent; - color: var(--color-text); - font-weight: 700; - cursor: pointer; -} - -.save:hover { - background: var(--color-surface-muted); -} - -.save svg { - width: 1.25rem; - height: 1.25rem; - fill: none; - stroke: var(--color-brand); - stroke-width: 2; -} - -.save[aria-pressed='true'] svg { - fill: var(--color-brand); -} - -@media (prefers-color-scheme: dark) { - .save svg { - stroke: var(--cork-300); - } - - .save[aria-pressed='true'] svg { - fill: var(--cork-300); - } -} - .facts, .foods { display: grid; diff --git a/frontend/src/features/wine/WineView.tsx b/frontend/src/features/wine/WineView.tsx index c32f3ae..b6c0270 100644 --- a/frontend/src/features/wine/WineView.tsx +++ b/frontend/src/features/wine/WineView.tsx @@ -4,9 +4,8 @@ import { Bottle } from '../../components/ui/Bottle'; import { ChipLink } from '../../components/ui/Chip'; import { EmptyState } from '../../components/ui/EmptyState'; import { ErrorNotice } from '../../components/ui/ErrorNotice'; -import { HeartIcon } from '../../components/ui/HeartIcon'; import { Skeleton } from '../../components/ui/Skeleton'; -import { useWishlist } from '../../hooks/useWishlist'; +import { WineListButtons } from '../lists/components/WineListButtons'; import { formatAbv, formatRating, pluralize } from '../../lib/format'; import { buildSearchUrl } from '../../lib/searchParams'; import type { WineDetails } from '../../lib/types'; @@ -79,7 +78,6 @@ export function WineView({ wine, loading, error, refetch, notFound }: WineViewPr } function WineDetailsView({ wine }: { wine: WineDetails }) { - const { isSaved, toggle } = useWishlist(wine.id); const origin = [wine.country, wine.region].filter(Boolean).join(', '); return ( @@ -110,10 +108,7 @@ function WineDetailsView({ wine }: { wine: WineDetails }) { )} - +
diff --git a/frontend/src/features/wine/api/toWineDetails.test.ts b/frontend/src/features/wine/api/toWineDetails.test.ts index f544641..522c097 100644 --- a/frontend/src/features/wine/api/toWineDetails.test.ts +++ b/frontend/src/features/wine/api/toWineDetails.test.ts @@ -19,6 +19,7 @@ const apiWine: ApiWineDetails = { vintages: [2020, 2005, 2012], communityRating: 4.1, communityRatingCount: 12, + myLists: [], }; describe('toWineDetails', () => { diff --git a/frontend/src/features/wine/api/wineQuery.ts b/frontend/src/features/wine/api/wineQuery.ts index e217d21..589c45b 100644 --- a/frontend/src/features/wine/api/wineQuery.ts +++ b/frontend/src/features/wine/api/wineQuery.ts @@ -20,6 +20,7 @@ export const WINE_QUERY = gql` vintages communityRating communityRatingCount + myLists } } `; diff --git a/frontend/src/features/wine/components/SimilarWines.test.tsx b/frontend/src/features/wine/components/SimilarWines.test.tsx index 7424523..e970b9d 100644 --- a/frontend/src/features/wine/components/SimilarWines.test.tsx +++ b/frontend/src/features/wine/components/SimilarWines.test.tsx @@ -5,6 +5,8 @@ import { MockedProvider } from '@apollo/client/testing/react'; import { MemoryRouter } from 'react-router'; import { axe } from 'vitest-axe'; import { createApolloCache } from '../../../lib/apollo'; +import { AuthProvider } from '../../auth/AuthProvider'; +import { meMock } from '../../../test/authMocks'; import type { WineDetails } from '../../../lib/types'; import { SEARCH_WINES_QUERY } from '../../search/api/searchQuery'; import { SimilarWines } from './SimilarWines'; @@ -39,6 +41,7 @@ const apiWine = (id: string, name: string) => ({ wineryName: 'Produsent', communityRating: 4, communityRatingCount: 10, + myLists: [], }); /** One answer to the query the section sends for a wine with Merlot. */ @@ -67,9 +70,12 @@ function similar(wines: { id: string; name: string }[]): MockLink.MockedResponse function renderSimilar(mocks: MockLink.MockedResponse[], wine = WINE) { return render( - + - + {/* The wine cards have list buttons, which need to know who is logged in. */} + + + , ); diff --git a/frontend/src/hooks/useWishlist.test.tsx b/frontend/src/hooks/useWishlist.test.tsx deleted file mode 100644 index 3496ad9..0000000 --- a/frontend/src/hooks/useWishlist.test.tsx +++ /dev/null @@ -1,42 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { act, renderHook } from '@testing-library/react'; -import { useWishlist } from './useWishlist'; - -const STORAGE_KEY = 'kk:wishlist'; - -describe('useWishlist', () => { - it('saves a wine in the browser and removes it again', () => { - const { result } = renderHook(() => useWishlist('1')); - expect(result.current.isSaved).toBe(false); - - act(() => result.current.toggle()); - expect(result.current.isSaved).toBe(true); - expect(window.localStorage.getItem(STORAGE_KEY)).toBe('["1"]'); - - act(() => result.current.toggle()); - expect(result.current.isSaved).toBe(false); - }); - - it('treats broken data in storage as an empty list', () => { - window.localStorage.setItem(STORAGE_KEY, '{not json'); - const { result } = renderHook(() => useWishlist('1')); - expect(result.current.isSaved).toBe(false); - }); - - it('ignores stored data that is not a list of ids', () => { - window.localStorage.setItem(STORAGE_KEY, '{"1":true}'); - const { result } = renderHook(() => useWishlist('1')); - expect(result.current.isSaved).toBe(false); - }); - - it('notices changes from another tab', () => { - const { result } = renderHook(() => useWishlist('1')); - - act(() => { - window.localStorage.setItem(STORAGE_KEY, '["1"]'); - window.dispatchEvent(new StorageEvent('storage', { key: STORAGE_KEY })); - }); - - expect(result.current.isSaved).toBe(true); - }); -}); diff --git a/frontend/src/hooks/useWishlist.ts b/frontend/src/hooks/useWishlist.ts deleted file mode 100644 index b891784..0000000 --- a/frontend/src/hooks/useWishlist.ts +++ /dev/null @@ -1,69 +0,0 @@ -import { useCallback, useSyncExternalStore } from 'react'; - -/* - * «Vil prøve»-liste lagret lokalt i nettleseren. - * - * MIDLERTIDIG: Når backend er på plass, byttes innmaten ut med - * `setListStatus(wineId, status)`-mutasjonen og Apollo-cachen - * (evt. en reactive var). Signaturen `{ isSaved, toggle }` skal - * beholdes, slik at WineCard og andre komponenter ikke må endres. - */ -const STORAGE_KEY = 'kk:wishlist'; -const listeners = new Set<() => void>(); - -function read(): string[] { - try { - const raw = window.localStorage.getItem(STORAGE_KEY); - const parsed: unknown = raw ? JSON.parse(raw) : []; - return Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === 'string') : []; - } catch { - // Privat modus, full lagring eller ødelagt JSON – fall tilbake til tom liste. - return []; - } -} - -function write(ids: string[]) { - try { - window.localStorage.setItem(STORAGE_KEY, JSON.stringify(ids)); - } catch { - // Ignorer: lista virker da bare i denne økta. - } - listeners.forEach((notify) => notify()); -} - -let snapshot = ''; -function getSnapshot(): string { - const next = read().join(','); - if (next !== snapshot) snapshot = next; - return snapshot; -} - -function subscribe(listener: () => void) { - listeners.add(listener); - const onStorage = (event: StorageEvent) => { - if (event.key === STORAGE_KEY) listener(); - }; - window.addEventListener('storage', onStorage); - return () => { - listeners.delete(listener); - window.removeEventListener('storage', onStorage); - }; -} - -export function useWishlist(wineId: string) { - const ids = useSyncExternalStore(subscribe, getSnapshot, () => ''); - const isSaved = ids.split(',').includes(wineId); - - const toggle = useCallback(() => { - const current = read(); - write(current.includes(wineId) ? current.filter((id) => id !== wineId) : [...current, wineId]); - }, [wineId]); - - return { isSaved, toggle }; -} - -/** The whole «Vil prøve» list, newest first. Updates when a heart is clicked. */ -export function useWishlistIds(): string[] { - const ids = useSyncExternalStore(subscribe, getSnapshot, () => ''); - return ids ? ids.split(',').reverse() : []; -} diff --git a/frontend/src/lib/apollo.test.ts b/frontend/src/lib/apollo.test.ts index 539e670..1c50258 100644 --- a/frontend/src/lib/apollo.test.ts +++ b/frontend/src/lib/apollo.test.ts @@ -1,6 +1,12 @@ -import { describe, expect, it } from 'vitest'; -import { gql } from '@apollo/client'; -import { createApolloCache, mergeWineConnection, type WineConnection } from './apollo'; +import { describe, expect, it, vi } from 'vitest'; +import { ApolloClient, ApolloLink, gql } from '@apollo/client'; +import { MockLink } from '@apollo/client/testing'; +import { + createApolloCache, + createSessionLink, + mergeWineConnection, + type WineConnection, +} from './apollo'; const connection = (ids: string[], hasNextPage = true): WineConnection => ({ totalCount: 10, @@ -61,3 +67,139 @@ describe('createApolloCache', () => { expect(keys).toHaveLength(2); }); }); + +describe('createApolloCache – User.wines', () => { + const LIST = gql` + query List($list: WineList!, $after: String) { + me { + id + wines(list: $list, after: $after) { + totalCount + edges { + cursor + node { + id + } + } + pageInfo { + hasNextPage + endCursor + } + } + } + } + `; + const page = (list: string, ids: string[], after?: string) => ({ + query: LIST, + variables: { list, after }, + data: { + me: { + __typename: 'User', + id: '1', + wines: { + __typename: 'WineConnection', + totalCount: 3, + edges: ids.map((id) => ({ + __typename: 'WineEdge', + cursor: id, + node: { __typename: 'Wine', id }, + })), + pageInfo: { __typename: 'PageInfo', hasNextPage: true, endCursor: ids.at(-1) ?? null }, + }, + }, + }, + }); + const idsOn = (cache: ReturnType, list: string) => + cache + .readQuery<{ me: { wines: { edges: { node: { id: string } }[] } } }>({ + query: LIST, + variables: { list }, + }) + ?.me.wines.edges.map((edge) => edge.node.id); + + it('keeps each list apart, and adds the next page of a list after the first', () => { + const cache = createApolloCache(); + cache.writeQuery(page('FAVOURITE', ['1', '2'])); + cache.writeQuery(page('TRIED', ['9'])); + cache.writeQuery(page('FAVOURITE', ['3'], '2')); + + expect(idsOn(cache, 'FAVOURITE')).toEqual(['1', '2', '3']); + expect(idsOn(cache, 'TRIED')).toEqual(['9']); + }); +}); + +describe('createSessionLink', () => { + const ME = gql` + query Me { + me { + id + username + } + } + `; + const SAVE = gql` + mutation Save($id: ID!) { + save(id: $id) + } + `; + const USER = { __typename: 'User', id: '1', username: 'kari' }; + + /** A client whose server answers `me` with the user first, and null after that. */ + function setup(saveResult: MockLink.MockedResponse['result']) { + const meAnswer = (me: typeof USER | null): MockLink.MockedResponse => ({ + request: { query: ME }, + result: { data: { me } }, + }); + // Counts the `me` requests when they are sent, not when the mock answers. + const meRequests = vi.fn(); + const counter = new ApolloLink((operation, forward) => { + if (operation.operationName === 'Me') meRequests(); + return forward(operation); + }); + const server = new MockLink([ + meAnswer(USER), + { request: { query: SAVE, variables: { id: '1' } }, result: saveResult }, + meAnswer(null), + ]); + const client = new ApolloClient({ + link: ApolloLink.from([createSessionLink(), counter, server]), + cache: createApolloCache(), + }); + // An active `me` query, like the one in AuthProvider. + const seen: unknown[] = []; + const subscription = client.watchQuery({ query: ME }).subscribe(({ data }) => seen.push(data)); + return { client, meRequests, seen, stop: () => subscription.unsubscribe() }; + } + + it('fetches `me` again when the API says the session has ended', async () => { + const { client, meRequests, seen, stop } = setup({ + errors: [{ message: 'You must be logged in.', extensions: { code: 'UNAUTHENTICATED' } }], + }); + await vi.waitFor(() => expect(seen.at(-1)).toEqual({ me: USER })); + + await expect(client.mutate({ mutation: SAVE, variables: { id: '1' } })).rejects.toThrow( + 'You must be logged in.', + ); + + await vi.waitFor(() => expect(seen.at(-1)).toEqual({ me: null })); + expect(meRequests).toHaveBeenCalledTimes(2); + stop(); + }); + + it('leaves `me` alone after other errors', async () => { + const { client, meRequests, seen, stop } = setup({ + errors: [{ message: 'Wine not found.', extensions: { code: 'BAD_USER_INPUT' } }], + }); + await vi.waitFor(() => expect(seen.at(-1)).toEqual({ me: USER })); + + await expect(client.mutate({ mutation: SAVE, variables: { id: '1' } })).rejects.toThrow( + 'Wine not found.', + ); + + // A refetch would be sent while the error passes through the link, before the mutation + // rejects. One more turn of the event loop leaves room for it, so its absence means something. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(meRequests).toHaveBeenCalledOnce(); + stop(); + }); +}); diff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.ts index f4d872d..ac176ec 100644 --- a/frontend/src/lib/apollo.ts +++ b/frontend/src/lib/apollo.ts @@ -1,4 +1,6 @@ -import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'; +import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client'; +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. */ export interface WineConnection { @@ -31,6 +33,18 @@ export function createApolloCache() { typePolicies: { // The landing page and the search page ask for different groups of the same object. FilterOptions: { merge: true }, + User: { + fields: { + // One list per name (FAVOURITE, WANT_TO_TRY, TRIED), with its pages added after each + // other like the search results. See also updateListPages in features/lists. + wines: { + keyArgs: ['list'], + merge(existing: WineConnection | undefined, incoming: WineConnection, { args }) { + return mergeWineConnection(existing, incoming, args?.after as string | undefined); + }, + }, + }, + }, Query: { fields: { wines: { @@ -47,8 +61,27 @@ export function createApolloCache() { }); } +/** + * When the API says UNAUTHENTICATED, the session has ended while the page was open: it expired, + * or the user logged out in another tab. `me` is then fetched again, so the whole app sees that + * nobody is logged in (the header, the review form and the list buttons) instead of going on as + * if the user still were. The failed request still fails, so the page can say what went wrong. + */ +export function createSessionLink() { + return new ErrorLink(({ error, operation }) => { + if (operation.operationName === 'Me') return; // `me` answers null, never UNAUTHENTICATED + const unauthenticated = + CombinedGraphQLErrors.is(error) && + error.errors.some((graphQLError) => graphQLError.extensions?.code === 'UNAUTHENTICATED'); + if (unauthenticated) void operation.client.refetchQueries({ include: ['Me'] }); + }); +} + /** BASE_URL makes the endpoint /project2/graphql both on the VM and in development. */ export const apolloClient = new ApolloClient({ - link: new HttpLink({ uri: `${import.meta.env.BASE_URL}graphql` }), + link: ApolloLink.from([ + createSessionLink(), + new HttpLink({ uri: `${import.meta.env.BASE_URL}graphql` }), + ]), cache: createApolloCache(), }); diff --git a/frontend/src/lib/mapWine.test.ts b/frontend/src/lib/mapWine.test.ts index caa0f3b..f90b9d2 100644 --- a/frontend/src/lib/mapWine.test.ts +++ b/frontend/src/lib/mapWine.test.ts @@ -11,6 +11,7 @@ const apiWine: ApiWine = { wineryName: 'Domaine Drouhin', communityRating: 4.88, communityRatingCount: 8, + myLists: [], }; describe('toWineType', () => { diff --git a/frontend/src/lib/mapWine.ts b/frontend/src/lib/mapWine.ts index 955d879..ae03665 100644 --- a/frontend/src/lib/mapWine.ts +++ b/frontend/src/lib/mapWine.ts @@ -1,4 +1,5 @@ import { formatCountry } from './format'; +import type { WineListName } from './wineLists'; import type { WineSummary, WineType } from './types'; /** The wine fields the frontend reads from the GraphQL API. */ @@ -12,6 +13,11 @@ export interface ApiWine { wineryName: string | null; communityRating: number | null; communityRatingCount: number; + /** + * The logged-in user's lists with this wine on them. Not used here: it is asked for in the + * same query as the wine, so the list buttons can read it from the cache (useWineList). + */ + myLists: WineListName[]; } /** The API uses the type names from X-Wines. "Dessert/Port" is our "Sterkvin". */ diff --git a/frontend/src/lib/wineLists.test.ts b/frontend/src/lib/wineLists.test.ts new file mode 100644 index 0000000..6c84fd0 --- /dev/null +++ b/frontend/src/lib/wineLists.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest'; +import { listsAfterChange } from './wineLists'; + +describe('listsAfterChange', () => { + it('puts a wine on a list and takes it off again', () => { + expect(listsAfterChange([], 'FAVOURITE', true)).toEqual(['FAVOURITE']); + expect(listsAfterChange(['FAVOURITE'], 'FAVOURITE', false)).toEqual([]); + }); + + it('changes nothing when the wine is already where it should be', () => { + expect(listsAfterChange(['FAVOURITE'], 'FAVOURITE', true)).toEqual(['FAVOURITE']); + expect(listsAfterChange([], 'TRIED', false)).toEqual([]); + }); + + it('keeps the same order as the API, whatever the order of the changes', () => { + expect(listsAfterChange(['TRIED'], 'FAVOURITE', true)).toEqual(['FAVOURITE', 'TRIED']); + }); + + it('takes the wine off «Vil prøve» when it goes on «Har prøvd», but not the other way', () => { + expect(listsAfterChange(['FAVOURITE', 'WANT_TO_TRY'], 'TRIED', true)).toEqual([ + 'FAVOURITE', + 'TRIED', + ]); + expect(listsAfterChange(['TRIED'], 'WANT_TO_TRY', true)).toEqual(['WANT_TO_TRY', 'TRIED']); + expect(listsAfterChange(['WANT_TO_TRY', 'TRIED'], 'TRIED', false)).toEqual(['WANT_TO_TRY']); + }); +}); diff --git a/frontend/src/lib/wineLists.ts b/frontend/src/lib/wineLists.ts new file mode 100644 index 0000000..5f99ff4 --- /dev/null +++ b/frontend/src/lib/wineLists.ts @@ -0,0 +1,20 @@ +/** The lists a user can put a wine on. The same values as the enum WineList in the API. */ +export const WINE_LISTS = ['FAVOURITE', 'WANT_TO_TRY', 'TRIED'] as const; +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. + */ +export function listsAfterChange( + current: readonly WineListName[], + list: WineListName, + inList: boolean, +): WineListName[] { + const next = new Set(current); + if (inList) next.add(list); + else next.delete(list); + if (inList && list === 'TRIED') next.delete('WANT_TO_TRY'); + return WINE_LISTS.filter((name) => next.has(name)); +} diff --git a/frontend/src/test/AuthReady.tsx b/frontend/src/test/AuthReady.tsx new file mode 100644 index 0000000..f9e4652 --- /dev/null +++ b/frontend/src/test/AuthReady.tsx @@ -0,0 +1,10 @@ +import { useAuth } from '../features/auth/useAuth'; + +/** + * Shown once AuthProvider knows who is logged in. The list buttons ignore a click before that, + * on purpose, so tests that click them wait for this first: `await screen.findByTestId('auth-ready')`. + */ +export function AuthReady() { + const { loading } = useAuth(); + return loading ? null : ; +} diff --git a/frontend/src/test/authMocks.ts b/frontend/src/test/authMocks.ts new file mode 100644 index 0000000..e3cfe4c --- /dev/null +++ b/frontend/src/test/authMocks.ts @@ -0,0 +1,22 @@ +import type { MockLink } from '@apollo/client/testing'; +import { ME_QUERY } from '../features/auth/api/authQueries'; + +/** A logged-in user, as `me` returns it. */ +export const TEST_USER = { + __typename: 'User', + id: '1', + username: 'kari', + createdAt: '2026-11-19T12:00:00.000Z', +}; + +/** + * Who is logged in, for tests that render AuthProvider. Answers every time `me` is asked for, + * for tests where the page asks again (after a login, or when the session has ended). + */ +export function meMock(user: typeof TEST_USER | null = null): MockLink.MockedResponse { + return { + request: { query: ME_QUERY }, + result: { data: { me: user } }, + maxUsageCount: Number.POSITIVE_INFINITY, + }; +} diff --git a/frontend/src/test/render.tsx b/frontend/src/test/render.tsx index 66fd72e..04c3c31 100644 --- a/frontend/src/test/render.tsx +++ b/frontend/src/test/render.tsx @@ -1,22 +1,34 @@ import type { ReactElement } from 'react'; import { render } 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 { AuthProvider } from '../features/auth/AuthProvider'; +import { createApolloCache } from '../lib/apollo'; +import { meMock } from './authMocks'; import { LocationProbe } from './LocationProbe'; /** - * Rendrer et element inne i en MemoryRouter. - * Bruk `screen.getByTestId('location')` for å sjekke navigasjon. + * Rendrer et element inne i en MemoryRouter, med Apollo og innlogging som i appen. + * Uten `mocks` er ingen logget inn. Bruk `screen.getByTestId('location')` for å sjekke navigasjon. */ -export function renderWithRouter(ui: ReactElement, { route = '/' }: { route?: string } = {}) { +export function renderWithRouter( + ui: ReactElement, + { route = '/', mocks = [meMock()] }: { route?: string; mocks?: MockLink.MockedResponse[] } = {}, +) { const user = userEvent.setup(); const result = render( - - - - - - , + + + + + + + + + + , ); return { user, ...result }; } diff --git a/frontend/src/test/searchMocks.ts b/frontend/src/test/searchMocks.ts index 46f139b..d95142f 100644 --- a/frontend/src/test/searchMocks.ts +++ b/frontend/src/test/searchMocks.ts @@ -22,6 +22,7 @@ const wine = (id: number): ApiWine & { __typename: string } => ({ wineryName: 'Produsent', communityRating: 4, communityRatingCount: 10, + myLists: [], }); /** One page from a catalogue of `total` wines, in the same shape as the API. */