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() { } /> } /> } /> - - } - /> + } /> ({ + __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 new file mode 100644 index 0000000..d921ff0 --- /dev/null +++ b/frontend/src/features/my/MyPage.tsx @@ -0,0 +1,10 @@ +import { useDocumentTitle } from '../../hooks/useDocumentTitle'; +import { useWishlistWines } from './api/useWishlistWines'; +import { MyView } from './MyView'; + +/** Route component for `/mine`. Connects the data source to the presentation. */ +export default function MyPage() { + useDocumentTitle('Mine anmeldelser'); + const result = useWishlistWines(); + return ; +} diff --git a/frontend/src/features/my/MyView.module.css b/frontend/src/features/my/MyView.module.css new file mode 100644 index 0000000..dca751d --- /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); +} diff --git a/frontend/src/features/my/MyView.tsx b/frontend/src/features/my/MyView.tsx new file mode 100644 index 0000000..dbe5ec9 --- /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. +

+
+
+ ); +} diff --git a/frontend/src/features/my/api/useWishlistWines.ts b/frontend/src/features/my/api/useWishlistWines.ts new file mode 100644 index 0000000..224c0bd --- /dev/null +++ b/frontend/src/features/my/api/useWishlistWines.ts @@ -0,0 +1,44 @@ +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 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 new file mode 100644 index 0000000..6b44142 --- /dev/null +++ b/frontend/src/features/my/api/wishlistQuery.ts @@ -0,0 +1,53 @@ +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/hooks/useWishlist.ts b/frontend/src/hooks/useWishlist.ts index 5c003d2..b891784 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() : []; +}