From 023898c302b504f6e123fa08f8eaef7ff2066f3c Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Fri, 13 Nov 2026 12:40:25 +0100 Subject: [PATCH 1/2] =?UTF-8?q?feat(my):=20show=20the=20wishlist=20on=20th?= =?UTF-8?q?e=20=C2=ABMine=20anmeldelser=C2=BB=20page=20(#56)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/app/App.tsx | 8 +-- frontend/src/features/my/MyPage.tsx | 10 ++++ frontend/src/features/my/MyView.module.css | 15 ++++++ frontend/src/features/my/MyView.tsx | 51 +++++++++++++++++++ .../src/features/my/api/useWishlistWines.ts | 42 +++++++++++++++ frontend/src/features/my/api/wishlistQuery.ts | 44 ++++++++++++++++ frontend/src/hooks/useWishlist.ts | 6 +++ 7 files changed, 170 insertions(+), 6 deletions(-) create mode 100644 frontend/src/features/my/MyPage.tsx create mode 100644 frontend/src/features/my/MyView.module.css create mode 100644 frontend/src/features/my/MyView.tsx create mode 100644 frontend/src/features/my/api/useWishlistWines.ts create mode 100644 frontend/src/features/my/api/wishlistQuery.ts diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx index c1b1b76..a293b43 100644 --- a/frontend/src/app/App.tsx +++ b/frontend/src/app/App.tsx @@ -7,6 +7,7 @@ import PlaceholderPage from './PlaceholderPage'; const LandingPage = lazy(() => import('../features/landing/LandingPage')); const SearchPage = lazy(() => import('../features/search/SearchPage')); const WinePage = lazy(() => import('../features/wine/WinePage')); +const MyPage = lazy(() => import('../features/my/MyPage')); /** BASE_URL kommer fra `base` i vite.config.ts (f.eks. «/project2/»). */ const basename = import.meta.env.BASE_URL.replace(/\/$/, '') || '/'; @@ -18,12 +19,7 @@ export function AppRoutes() { } /> } /> } /> - - } - /> + } /> ; +} \ No newline at end of file diff --git a/frontend/src/features/my/MyView.module.css b/frontend/src/features/my/MyView.module.css new file mode 100644 index 0000000..c1bd1fe --- /dev/null +++ b/frontend/src/features/my/MyView.module.css @@ -0,0 +1,15 @@ +.page { + display: grid; + gap: var(--space-6); + padding-block: var(--space-7); +} + +.count { + margin-bottom: var(--space-3); + color: var(--color-text-muted); +} + +.empty { + margin-top: var(--space-2); + color: var(--color-text-muted); +} \ No newline at end of file diff --git a/frontend/src/features/my/MyView.tsx b/frontend/src/features/my/MyView.tsx new file mode 100644 index 0000000..3575ea0 --- /dev/null +++ b/frontend/src/features/my/MyView.tsx @@ -0,0 +1,51 @@ +import { Link } from 'react-router'; +import { ErrorNotice } from '../../components/ui/ErrorNotice'; +import { Skeleton } from '../../components/ui/Skeleton'; +import { WineList } from '../../components/ui/WineList'; +import { pluralize } from '../../lib/format'; +import { buildSearchUrl } from '../../lib/searchParams'; +import type { WishlistResult } from './api/useWishlistWines'; +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) { + return ( +
+

Mine anmeldelser

+ +
+

Vil prøve

+ +

+ {loading ? 'Laster viner …' : ''} +

+ + {savedCount === 0 ? ( +

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

+ ) : ( + <> +

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

+ + {loading && wines.length === 0 && } + + {error && ( + + )} + + {wines.length > 0 && } + + )} +
+ +
+

Mine dommer

+

+ Dommene dine vises her når innlogging er på plass. Fram til da finner du dem på vinsiden. +

+
+
+ ); +} \ No newline at end of file diff --git a/frontend/src/features/my/api/useWishlistWines.ts b/frontend/src/features/my/api/useWishlistWines.ts new file mode 100644 index 0000000..8d741f0 --- /dev/null +++ b/frontend/src/features/my/api/useWishlistWines.ts @@ -0,0 +1,42 @@ +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(); + + // A new query object on every render would make Apollo fetch again in a loop. + const query = useMemo(() => wishlistQuery(ids), [ids.join(',')]); + + 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), + }; +} \ No newline at end of file diff --git a/frontend/src/features/my/api/wishlistQuery.ts b/frontend/src/features/my/api/wishlistQuery.ts new file mode 100644 index 0000000..3477fa2 --- /dev/null +++ b/frontend/src/features/my/api/wishlistQuery.ts @@ -0,0 +1,44 @@ +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[]) { + 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])); +} \ No newline at end of file diff --git a/frontend/src/hooks/useWishlist.ts b/frontend/src/hooks/useWishlist.ts index 5c003d2..482e202 100644 --- a/frontend/src/hooks/useWishlist.ts +++ b/frontend/src/hooks/useWishlist.ts @@ -61,3 +61,9 @@ export function useWishlist(wineId: string) { 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() : []; +} \ No newline at end of file From 37521b3307270a76cb6e8734db7e4f545165e09f Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Fri, 13 Nov 2026 12:45:33 +0100 Subject: [PATCH 2/2] feat(my): show the wishlist with wines from the API (#56) --- frontend/src/features/my/MyPage.test.tsx | 115 ++++++++++++++++++ frontend/src/features/my/MyPage.tsx | 2 +- frontend/src/features/my/MyView.module.css | 2 +- frontend/src/features/my/MyView.tsx | 2 +- .../src/features/my/api/useWishlistWines.ts | 6 +- .../src/features/my/api/wishlistQuery.test.ts | 25 ++++ frontend/src/features/my/api/wishlistQuery.ts | 11 +- frontend/src/hooks/useWishlist.ts | 2 +- 8 files changed, 158 insertions(+), 7 deletions(-) create mode 100644 frontend/src/features/my/MyPage.test.tsx create mode 100644 frontend/src/features/my/api/wishlistQuery.test.ts diff --git a/frontend/src/features/my/MyPage.test.tsx b/frontend/src/features/my/MyPage.test.tsx new file mode 100644 index 0000000..b620865 --- /dev/null +++ b/frontend/src/features/my/MyPage.test.tsx @@ -0,0 +1,115 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { render, screen, 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 MyPage from './MyPage'; +import { wishlistQuery, wishlistVariables } from './api/wishlistQuery'; + +const WISHLIST_KEY = 'kk:wishlist'; + +const apiWine = (id: string, name: string, type = 'Red') => ({ + __typename: 'Wine', + id, + name, + type, + grapes: ['Merlot'], + country: 'Italy', + countryCode: 'IT', + wineryName: 'Produsent', + communityRating: 4.2, + communityRatingCount: 12, +}); + +/** 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); + return { + request: { query: wishlistQuery(ids), variables: wishlistVariables(ids) }, + result: { + data: Object.fromEntries( + saved.map((wine, index) => [`wine${index}`, apiWine(wine.id, wine.name)]), + ), + }, + }; +} + +/** 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()); + +describe('MyPage', () => { + it('explains the empty list and links to the search', () => { + renderPage([]); + expect(screen.getByText(/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']); + renderPage([ + wines([ + { 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(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' }])]); + + await user.click(await screen.findByRole('button', { name: 'Vil prøve Origem Merlot' })); + + expect(screen.getByText(/Du har ikke lagret noen viner ennå/)).toBeInTheDocument(); + }); + + it('offers a new attempt when the wines cannot be fetched', async () => { + save(['100062']); + renderPage([ + { + request: { + query: wishlistQuery(['100062']), + variables: wishlistVariables(['100062']), + }, + error: new Error('Nede'), + }, + ]); + + expect(await screen.findByRole('alert')).toHaveTextContent('Vi fikk ikke hentet vinene'); + expect(screen.getByRole('button', { name: 'Prøv igjen' })).toBeInTheDocument(); + }); + + it('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' }); + expect(await axe(container)).toHaveNoViolations(); + }); +}); diff --git a/frontend/src/features/my/MyPage.tsx b/frontend/src/features/my/MyPage.tsx index c1a5334..d921ff0 100644 --- a/frontend/src/features/my/MyPage.tsx +++ b/frontend/src/features/my/MyPage.tsx @@ -7,4 +7,4 @@ export default function MyPage() { useDocumentTitle('Mine anmeldelser'); const result = useWishlistWines(); return ; -} \ No newline at end of file +} diff --git a/frontend/src/features/my/MyView.module.css b/frontend/src/features/my/MyView.module.css index c1bd1fe..dca751d 100644 --- a/frontend/src/features/my/MyView.module.css +++ b/frontend/src/features/my/MyView.module.css @@ -12,4 +12,4 @@ .empty { margin-top: var(--space-2); color: var(--color-text-muted); -} \ No newline at end of file +} diff --git a/frontend/src/features/my/MyView.tsx b/frontend/src/features/my/MyView.tsx index 3575ea0..dbe5ec9 100644 --- a/frontend/src/features/my/MyView.tsx +++ b/frontend/src/features/my/MyView.tsx @@ -48,4 +48,4 @@ export function MyView({ wines, savedCount, loading, error, refetch }: WishlistR ); -} \ No newline at end of file +} diff --git a/frontend/src/features/my/api/useWishlistWines.ts b/frontend/src/features/my/api/useWishlistWines.ts index 8d741f0..224c0bd 100644 --- a/frontend/src/features/my/api/useWishlistWines.ts +++ b/frontend/src/features/my/api/useWishlistWines.ts @@ -17,9 +17,11 @@ export interface WishlistResult { /** 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(ids), [ids.join(',')]); + const query = useMemo(() => wishlistQuery(key ? key.split(',') : []), [key]); const { data, loading, error, refetch } = useQuery(query, { variables: wishlistVariables(ids), @@ -39,4 +41,4 @@ export function useWishlistWines(): WishlistResult { error, refetch: () => void refetch().catch(() => undefined), }; -} \ No newline at end of file +} diff --git a/frontend/src/features/my/api/wishlistQuery.test.ts b/frontend/src/features/my/api/wishlistQuery.test.ts new file mode 100644 index 0000000..7256a4c --- /dev/null +++ b/frontend/src/features/my/api/wishlistQuery.test.ts @@ -0,0 +1,25 @@ +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 index 3477fa2..6b44142 100644 --- a/frontend/src/features/my/api/wishlistQuery.ts +++ b/frontend/src/features/my/api/wishlistQuery.ts @@ -12,6 +12,15 @@ export interface WishlistData { * 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) => ` @@ -41,4 +50,4 @@ export function wishlistQuery(ids: string[]) { /** { 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])); -} \ No newline at end of file +} diff --git a/frontend/src/hooks/useWishlist.ts b/frontend/src/hooks/useWishlist.ts index 482e202..b891784 100644 --- a/frontend/src/hooks/useWishlist.ts +++ b/frontend/src/hooks/useWishlist.ts @@ -66,4 +66,4 @@ export function useWishlist(wineId: string) { export function useWishlistIds(): string[] { const ids = useSyncExternalStore(subscribe, getSnapshot, () => ''); return ids ? ids.split(',').reverse() : []; -} \ No newline at end of file +}