From c87edfcb605f6413fd29b55c9c8c80394b1555bc Mon Sep 17 00:00:00 2001 From: Magnus Andreas Igesund Nerland Date: Thu, 19 Nov 2026 13:55:13 +0100 Subject: [PATCH 1/8] fix(frontend): refetch the user when the session ends, and review fixes from #65 (#72) --- frontend/src/features/auth/AuthProvider.tsx | 41 +++++---- .../auth/components/AuthForm.test.tsx | 14 +++ .../src/features/auth/components/AuthForm.tsx | 19 ++-- frontend/src/lib/apollo.test.ts | 88 ++++++++++++++++++- frontend/src/lib/apollo.ts | 25 +++++- 5 files changed, 158 insertions(+), 29 deletions(-) diff --git a/frontend/src/features/auth/AuthProvider.tsx b/frontend/src/features/auth/AuthProvider.tsx index db2adf7..d78273c 100644 --- a/frontend/src/features/auth/AuthProvider.tsx +++ b/frontend/src/features/auth/AuthProvider.tsx @@ -1,4 +1,5 @@ import { useCallback, type ReactNode } from 'react'; +import type { ApolloClient } from '@apollo/client'; import { useApolloClient, useMutation, useQuery } from '@apollo/client/react'; import { LOGIN_MUTATION, @@ -6,11 +7,24 @@ import { ME_QUERY, REGISTER_MUTATION, type MeData, - type User, } from './api/authQueries'; import { authErrorMessage, describeAuthError, type AuthFailure } from './api/authMessages'; import { AuthContext, type AuthContextValue, type Credentials } from './AuthContext'; +/** + * After a login or logout, everything in the cache was fetched as someone else: `me`, and data + * such as `myReview` and `myLists`. resetStore empties the cache and fetches the queries on the + * page again, `me` included, now with the new session cookie. The server is the one that knows + * who is logged in, so `me` is not written into the cache by hand. + * + * Not clearStore followed by writeQuery: clearStore also stops the cache from telling the queries + * on the page about changes, so the header would keep showing the old user. + */ +async function startOver(client: ApolloClient) { + // A query that fails to load again shows its own error, so the rejection needs no handling here. + await client.resetStore().catch(() => undefined); +} + /** * Keeps the logged-in user for the whole app. The session itself lives in an httpOnly * cookie that JavaScript cannot read, so `me` is what tells us who is logged in. @@ -22,20 +36,12 @@ export function AuthProvider({ children }: { children: ReactNode }) { const [loginMutation] = useMutation(LOGIN_MUTATION); const [logoutMutation] = useMutation(LOGOUT_MUTATION); - /** Runs a mutation and writes the new user into the cache, so the whole app sees it. */ + /** Runs a login or register mutation, and starts the cache over as the new user. */ const run = useCallback( - async ( - mutate: typeof loginMutation, - credentials: Credentials, - field: 'login' | 'register', - ): Promise => { + async (mutate: typeof loginMutation, credentials: Credentials): Promise => { try { - const result = await mutate({ variables: { input: credentials } }); - const user = (result.data as Record | null)?.[field] ?? null; - client.writeQuery({ query: ME_QUERY, data: { me: user } }); - // Data such as `myReview` was fetched as a visitor. Starting the cache over, like after - // logout, means no page shows another person's (or nobody's) data after a login. - await client.resetStore().catch(() => undefined); + await mutate({ variables: { input: credentials } }); + await startOver(client); return null; } catch (error) { return describeAuthError(error); @@ -47,8 +53,8 @@ export function AuthProvider({ children }: { children: ReactNode }) { const value: AuthContextValue = { user: data?.me ?? null, loading, - register: (credentials) => run(registerMutation, credentials, 'register'), - login: (credentials) => run(loginMutation, credentials, 'login'), + register: (credentials) => run(registerMutation, credentials), + login: (credentials) => run(loginMutation, credentials), logout: async (): Promise => { try { await logoutMutation(); @@ -58,10 +64,7 @@ export function AuthProvider({ children }: { children: ReactNode }) { return authErrorMessage(error); } - // The server has cleared the cookie. Everything cached was fetched as that - // user, so the store starts over. - client.writeQuery({ query: ME_QUERY, data: { me: null } }); - await client.resetStore().catch(() => undefined); + await startOver(client); return null; }, }; diff --git a/frontend/src/features/auth/components/AuthForm.test.tsx b/frontend/src/features/auth/components/AuthForm.test.tsx index b779409..6a65c53 100644 --- a/frontend/src/features/auth/components/AuthForm.test.tsx +++ b/frontend/src/features/auth/components/AuthForm.test.tsx @@ -107,6 +107,20 @@ describe('AuthForm', () => { await screen.findByRole('button', { name: 'Logg inn' }); }); + it('is ready again, with a message, when sending fails in a way it did not expect', async () => { + const onSubmit = vi.fn(() => Promise.reject(new Error('Unexpected'))); + const user = userEvent.setup(); + render(); + await fillIn(user, 'kari', PASSWORD); + + await user.click(screen.getByRole('button', { name: 'Logg inn' })); + + expect(await screen.findByRole('button', { name: 'Logg inn' })).not.toHaveAttribute( + 'aria-disabled', + ); + expect(screen.getByRole('alert')).toHaveTextContent('Noe uventet gikk galt. Prøv igjen.'); + }); + it('only shows the rules when creating a user', () => { renderForm('login'); expect(usernameField()).not.toHaveAccessibleDescription(); diff --git a/frontend/src/features/auth/components/AuthForm.tsx b/frontend/src/features/auth/components/AuthForm.tsx index be48b9c..6720fec 100644 --- a/frontend/src/features/auth/components/AuthForm.tsx +++ b/frontend/src/features/auth/components/AuthForm.tsx @@ -1,4 +1,5 @@ import { useId, useRef, useState, type FormEvent } from 'react'; +import { ERROR_DETAILS } from '../../../lib/errors'; import { reasonFailure, type AuthFailure } from '../api/authMessages'; import type { Credentials } from '../AuthContext'; import { @@ -66,11 +67,19 @@ export function AuthForm({ mode, onSubmit }: AuthFormProps) { if (Object.keys(errors).length > 0) return; setWorking(true); - const failure = await onSubmit({ - username: normalizeUsername(values.username), - password: values.password, - }); - setWorking(false); + let failure: AuthFailure | null; + try { + failure = await onSubmit({ + username: normalizeUsername(values.username), + password: values.password, + }); + } catch { + // onSubmit should answer with a message, but if it throws, the form must not stay stuck. + failure = { message: ERROR_DETAILS.unknown }; + } finally { + // Also when onSubmit throws, so the button never stays at «Logger inn …». + setWorking(false); + } if (failure?.field) { const errors: FieldErrors = {}; diff --git a/frontend/src/lib/apollo.test.ts b/frontend/src/lib/apollo.test.ts index 539e670..67b5f72 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,79 @@ describe('createApolloCache', () => { expect(keys).toHaveLength(2); }); }); + +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..dc22500 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 { @@ -47,8 +49,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(), }); From e02cdc1b5c6c4e770cc4aad4aa5bab1bf9ea78d6 Mon Sep 17 00:00:00 2001 From: Magnus Andreas Igesund Nerland Date: Thu, 19 Nov 2026 14:24:40 +0100 Subject: [PATCH 2/8] feat(frontend): useWineList against the API, with myLists in the wine queries (#72) --- frontend/e2e/filters.spec.ts | 1 + frontend/e2e/landing.spec.ts | 1 + frontend/e2e/screenreader.spec.ts | 1 + frontend/e2e/search.spec.ts | 1 + frontend/e2e/wine.spec.ts | 1 + .../src/features/landing/LandingPage.test.tsx | 1 + .../src/features/landing/api/landingQuery.ts | 1 + .../landing/api/toLandingData.test.ts | 1 + .../landing/api/useLandingData.test.tsx | 1 + .../src/features/lists/api/listQueries.ts | 28 +++ .../src/features/lists/useWineList.test.tsx | 213 ++++++++++++++++++ frontend/src/features/lists/useWineList.ts | 85 +++++++ frontend/src/features/my/MyPage.test.tsx | 1 + frontend/src/features/my/api/wishlistQuery.ts | 1 + .../src/features/search/api/searchQuery.ts | 1 + frontend/src/features/wine/WinePage.test.tsx | 1 + .../features/wine/api/toWineDetails.test.ts | 1 + frontend/src/features/wine/api/wineQuery.ts | 1 + .../wine/components/SimilarWines.test.tsx | 1 + frontend/src/lib/mapWine.test.ts | 1 + frontend/src/lib/mapWine.ts | 6 + frontend/src/lib/wineLists.test.ts | 27 +++ frontend/src/lib/wineLists.ts | 20 ++ frontend/src/test/searchMocks.ts | 1 + 24 files changed, 397 insertions(+) create mode 100644 frontend/src/features/lists/api/listQueries.ts create mode 100644 frontend/src/features/lists/useWineList.test.tsx create mode 100644 frontend/src/features/lists/useWineList.ts create mode 100644 frontend/src/lib/wineLists.test.ts create mode 100644 frontend/src/lib/wineLists.ts 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/screenreader.spec.ts b/frontend/e2e/screenreader.spec.ts index 39d59ae..f9a4fab 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) { 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..f258379 100644 --- a/frontend/e2e/wine.spec.ts +++ b/frontend/e2e/wine.spec.ts @@ -22,6 +22,7 @@ const wine = { vintages: [2020, 2005], communityRating: 4.12, communityRatingCount: 12, + myLists: [], }; const searchResult = { diff --git a/frontend/src/features/landing/LandingPage.test.tsx b/frontend/src/features/landing/LandingPage.test.tsx index 3968019..f2cf3bc 100644 --- a/frontend/src/features/landing/LandingPage.test.tsx +++ b/frontend/src/features/landing/LandingPage.test.tsx @@ -27,6 +27,7 @@ const mock = { wineryName: 'Produsent', communityRating: 4.5, communityRatingCount: 10, + myLists: [], }, }, ], diff --git a/frontend/src/features/landing/api/landingQuery.ts b/frontend/src/features/landing/api/landingQuery.ts index b98772f..32ea33e 100644 --- a/frontend/src/features/landing/api/landingQuery.ts +++ b/frontend/src/features/landing/api/landingQuery.ts @@ -19,6 +19,7 @@ export const LANDING_QUERY = gql` wineryName communityRating communityRatingCount + myLists } } } diff --git a/frontend/src/features/landing/api/toLandingData.test.ts b/frontend/src/features/landing/api/toLandingData.test.ts index 589f6bd..51900b2 100644 --- a/frontend/src/features/landing/api/toLandingData.test.ts +++ b/frontend/src/features/landing/api/toLandingData.test.ts @@ -12,6 +12,7 @@ const wine = (id: string, type = 'Red'): ApiWine => ({ wineryName: 'Winery', communityRating: 4, communityRatingCount: 10, + myLists: [], }); const query = (wines: ApiWine[] = [wine('1')]): LandingQueryData => ({ diff --git a/frontend/src/features/landing/api/useLandingData.test.tsx b/frontend/src/features/landing/api/useLandingData.test.tsx index c0f646d..78f571e 100644 --- a/frontend/src/features/landing/api/useLandingData.test.tsx +++ b/frontend/src/features/landing/api/useLandingData.test.tsx @@ -25,6 +25,7 @@ const result = { wineryName: 'Winery', communityRating: 4.2, communityRatingCount: 12, + myLists: [], }, }, ], diff --git a/frontend/src/features/lists/api/listQueries.ts b/frontend/src/features/lists/api/listQueries.ts new file mode 100644 index 0000000..476297a --- /dev/null +++ b/frontend/src/features/lists/api/listQueries.ts @@ -0,0 +1,28 @@ +import { gql } from '@apollo/client'; +import type { WineListName } from '../../../lib/wineLists'; + +/** + * The lists of one wine, read straight from the cache. The queries for wine cards and the wine + * page ask for `myLists` together with the wine, so a page of 24 wines needs no extra request. + */ +export const WINE_LISTS_FRAGMENT = gql` + fragment WineLists on Wine { + id + myLists + } +`; + +export interface WineListsFragment { + id: string; + myLists: WineListName[]; +} + +/** Returns the wine with its new lists, so every button for it in the cache updates. */ +export const SET_WINE_IN_LIST_MUTATION = gql` + mutation SetWineInList($wineId: ID!, $list: WineList!, $inList: Boolean!) { + setWineInList(wineId: $wineId, list: $list, inList: $inList) { + id + myLists + } + } +`; diff --git a/frontend/src/features/lists/useWineList.test.tsx b/frontend/src/features/lists/useWineList.test.tsx new file mode 100644 index 0000000..0b4efec --- /dev/null +++ b/frontend/src/features/lists/useWineList.test.tsx @@ -0,0 +1,213 @@ +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('removes the user’s list pages from the cache, so they are fetched again', async () => { + const { user, cache } = renderButtons([setWineInList('FAVOURITE', false, wineWith([]))], { + lists: ['FAVOURITE'], + }); + const LIST = gql` + query MyList { + me { + id + wines(list: FAVOURITE) { + totalCount + } + } + } + `; + cache.writeQuery({ + query: LIST, + data: { + me: { + __typename: 'User', + id: USER.id, + wines: { __typename: 'WineConnection', totalCount: 1 }, + }, + }, + }); + await ready(); + + await user.click(button('FAVOURITE')); + + await waitFor(() => expect(cache.readQuery({ query: LIST })).toBeNull()); + }); + + 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..c800b78 --- /dev/null +++ b/frontend/src/features/lists/useWineList.ts @@ -0,0 +1,85 @@ +import { useRef, useState } from 'react'; +import { useApolloClient, useFragment, useMutation } from '@apollo/client/react'; +import { useLocation, useNavigate } from 'react-router'; +import { classifyError, ERROR_DETAILS } from '../../lib/errors'; +import { listsAfterChange, type WineListName } from '../../lib/wineLists'; +import { useAuth } from '../auth/useAuth'; +import { + SET_WINE_IN_LIST_MUTATION, + WINE_LISTS_FRAGMENT, + 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 client = useApolloClient(); + const navigate = useNavigate(); + const location = useLocation(); + const [error, setError] = useState(null); + // One change at a time: a second click while the first is on its way is ignored, so two + // requests can never arrive in the wrong order and leave the list the wrong way round. + const pending = useRef(false); + const [setWineInList] = useMutation(SET_WINE_IN_LIST_MUTATION); + + 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), + }, + }, + }); + // The pages that list the user's wines (and the top 4) no longer match. Removing them from + // the cache makes a page that shows them fetch them again, and the others when next shown. + const userId = client.cache.identify({ __typename: 'User', id: user.id }); + client.cache.evict({ id: userId, fieldName: 'wines' }); + client.cache.evict({ id: userId, fieldName: 'topFavourites' }); + client.cache.gc(); + } 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..14f6cf8 100644 --- a/frontend/src/features/my/MyPage.test.tsx +++ b/frontend/src/features/my/MyPage.test.tsx @@ -22,6 +22,7 @@ const apiWine = (id: string, name: string, type = 'Red') => ({ wineryName: 'Produsent', communityRating: 4.2, communityRatingCount: 12, + myLists: [], }); /** One answer for the wines on the list, in the order the page asks for them. */ diff --git a/frontend/src/features/my/api/wishlistQuery.ts b/frontend/src/features/my/api/wishlistQuery.ts index 6b44142..e84f404 100644 --- a/frontend/src/features/my/api/wishlistQuery.ts +++ b/frontend/src/features/my/api/wishlistQuery.ts @@ -34,6 +34,7 @@ export function wishlistQuery(ids: string[]) { wineryName communityRating communityRatingCount + myLists }`, ) .join(''); 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..a7fd3a0 100644 --- a/frontend/src/features/wine/WinePage.test.tsx +++ b/frontend/src/features/wine/WinePage.test.tsx @@ -33,6 +33,7 @@ const wine = { vintages: [2020, 2005], communityRating: 4.12, communityRatingCount: 1234, + myLists: [], }; const found = (result = wine): MockLink.MockedResponse => ({ 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..33c28a9 100644 --- a/frontend/src/features/wine/components/SimilarWines.test.tsx +++ b/frontend/src/features/wine/components/SimilarWines.test.tsx @@ -39,6 +39,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. */ 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/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. */ From f9a8fe7dfada4ab703575069c8722328bb09fb37 Mon Sep 17 00:00:00 2001 From: Magnus Andreas Igesund Nerland Date: Thu, 19 Nov 2026 14:39:35 +0100 Subject: [PATCH 3/8] =?UTF-8?q?feat(frontend):=20favourite,=20=C2=ABVil=20?= =?UTF-8?q?pr=C3=B8ve=C2=BB=20and=20=C2=ABHar=20pr=C3=B8vd=C2=BB=20buttons?= =?UTF-8?q?=20on=20the=20wine=20page=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/e2e/wine.spec.ts | 59 +++++++-- frontend/src/components/ui/BookmarkIcon.tsx | 8 ++ frontend/src/components/ui/CheckIcon.tsx | 9 ++ frontend/src/components/ui/HeartIcon.tsx | 2 +- frontend/src/components/ui/index.ts | 2 + .../components/WineListButtons.module.css | 73 +++++++++++ .../lists/components/WineListButtons.test.tsx | 117 ++++++++++++++++++ .../lists/components/WineListButtons.tsx | 54 ++++++++ .../features/lists/components/listButtons.ts | 15 +++ frontend/src/features/wine/WinePage.test.tsx | 42 +++++-- .../src/features/wine/WineView.module.css | 40 ------ frontend/src/features/wine/WineView.tsx | 9 +- 12 files changed, 368 insertions(+), 62 deletions(-) create mode 100644 frontend/src/components/ui/BookmarkIcon.tsx create mode 100644 frontend/src/components/ui/CheckIcon.tsx create mode 100644 frontend/src/features/lists/components/WineListButtons.module.css create mode 100644 frontend/src/features/lists/components/WineListButtons.test.tsx create mode 100644 frontend/src/features/lists/components/WineListButtons.tsx create mode 100644 frontend/src/features/lists/components/listButtons.ts diff --git a/frontend/e2e/wine.spec.ts b/frontend/e2e/wine.spec.ts index f258379..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 = { @@ -36,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 }, @@ -55,6 +59,7 @@ async function stubApi(page: Page) { }), // Both the search page and «Lignende viner» on the wine page use SearchWines. SearchWines: () => searchResult, + ...overrides, }); } @@ -98,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/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 (
+ {/* 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/wine/WinePage.test.tsx b/frontend/src/features/wine/WinePage.test.tsx index a7fd3a0..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,7 +33,7 @@ const wine = { vintages: [2020, 2005], communityRating: 4.12, communityRatingCount: 1234, - myLists: [], + myLists: [] as string[], }; const found = (result = wine): MockLink.MockedResponse => ({ @@ -72,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: { @@ -199,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 }) { )} - +
From ef42e0bf30a898d8faedd73b702d819c369c7c99 Mon Sep 17 00:00:00 2001 From: Magnus Andreas Igesund Nerland Date: Thu, 19 Nov 2026 14:59:33 +0100 Subject: [PATCH 4/8] =?UTF-8?q?feat(frontend):=20list=20buttons=20on=20the?= =?UTF-8?q?=20wine=20cards,=20and=20=C2=ABVil=20pr=C3=B8ve=C2=BB=20from=20?= =?UTF-8?q?the=20API=20on=20=C2=ABMine=20anmeldelser=C2=BB=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/e2e/screenreader.spec.ts | 3 +- frontend/src/app/App.test.tsx | 3 +- frontend/src/app/App.tsx | 11 +- .../src/components/ui/WineCard.module.css | 42 ----- frontend/src/components/ui/WineCard.test.tsx | 71 +++++++-- frontend/src/components/ui/WineCard.tsx | 18 +-- .../src/features/landing/LandingPage.test.tsx | 9 +- .../src/features/lists/api/listCache.test.ts | 127 +++++++++++++++ frontend/src/features/lists/api/listCache.ts | 60 ++++++++ .../src/features/lists/api/listQueries.ts | 10 ++ .../src/features/lists/api/myWineListQuery.ts | 48 ++++++ .../src/features/lists/api/useMyWineList.ts | 71 +++++++++ .../components/WineCardListButtons.module.css | 56 +++++++ .../lists/components/WineCardListButtons.tsx | 52 +++++++ .../src/features/lists/useWineList.test.tsx | 27 +++- frontend/src/features/lists/useWineList.ts | 21 +-- frontend/src/features/my/MyPage.test.tsx | 144 ++++++++++++------ frontend/src/features/my/MyPage.tsx | 8 +- frontend/src/features/my/MyView.module.css | 21 +++ frontend/src/features/my/MyView.tsx | 115 ++++++++++---- .../src/features/my/api/useWishlistWines.ts | 44 ------ .../src/features/my/api/wishlistQuery.test.ts | 25 --- frontend/src/features/my/api/wishlistQuery.ts | 54 ------- .../features/search/SearchFilters.test.tsx | 17 ++- .../src/features/search/SearchPage.test.tsx | 19 ++- .../wine/components/SimilarWines.test.tsx | 9 +- frontend/src/hooks/useWishlist.test.tsx | 42 ----- frontend/src/hooks/useWishlist.ts | 69 --------- frontend/src/lib/apollo.test.ts | 60 ++++++++ frontend/src/lib/apollo.ts | 12 ++ frontend/src/test/AuthReady.tsx | 10 ++ frontend/src/test/authMocks.ts | 22 +++ frontend/src/test/render.tsx | 30 ++-- 33 files changed, 908 insertions(+), 422 deletions(-) create mode 100644 frontend/src/features/lists/api/listCache.test.ts create mode 100644 frontend/src/features/lists/api/listCache.ts create mode 100644 frontend/src/features/lists/api/myWineListQuery.ts create mode 100644 frontend/src/features/lists/api/useMyWineList.ts create mode 100644 frontend/src/features/lists/components/WineCardListButtons.module.css create mode 100644 frontend/src/features/lists/components/WineCardListButtons.tsx delete mode 100644 frontend/src/features/my/api/useWishlistWines.ts delete mode 100644 frontend/src/features/my/api/wishlistQuery.test.ts delete mode 100644 frontend/src/features/my/api/wishlistQuery.ts delete mode 100644 frontend/src/hooks/useWishlist.test.tsx delete mode 100644 frontend/src/hooks/useWishlist.ts create mode 100644 frontend/src/test/AuthReady.tsx create mode 100644 frontend/src/test/authMocks.ts diff --git a/frontend/e2e/screenreader.spec.ts b/frontend/e2e/screenreader.spec.ts index f9a4fab..59a7292 100644 --- a/frontend/e2e/screenreader.spec.ts +++ b/frontend/e2e/screenreader.spec.ts @@ -144,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/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/ui/WineCard.module.css b/frontend/src/components/ui/WineCard.module.css index faf2297..cf22807 100644 --- a/frontend/src/components/ui/WineCard.module.css +++ b/frontend/src/components/ui/WineCard.module.css @@ -111,48 +111,6 @@ color: var(--color-text); } -.save { - position: absolute; - z-index: 1; /* over den utvidede lenken */ - top: var(--space-2); - right: var(--space-2); - display: grid; - place-items: center; - width: var(--tap-target); - height: var(--tap-target); - padding: 0; - border: 0; - border-radius: 50%; - background: transparent; - cursor: pointer; -} - -.save svg { - width: 1.4rem; - height: 1.4rem; - fill: none; - stroke: var(--color-brand); - stroke-width: 2; - transition: fill var(--transition); -} - -.save:hover { - background: var(--color-surface-muted); -} - -.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); - } -} - /* Smale kort: stable vurderingene. */ @container (max-width: 20rem) { .ratingRow dt { diff --git a/frontend/src/components/ui/WineCard.test.tsx b/frontend/src/components/ui/WineCard.test.tsx index de76c10..9be5d7a 100644 --- a/frontend/src/components/ui/WineCard.test.tsx +++ b/frontend/src/components/ui/WineCard.test.tsx @@ -4,6 +4,9 @@ import { useLocation } from 'react-router'; import { axe } from 'vitest-axe'; import { renderWithRouter } from '../../test/render'; import type { WineSummary } from '../../lib/types'; +import { SET_WINE_IN_LIST_MUTATION } from '../../features/lists/api/listQueries'; +import { AuthReady } from '../../test/AuthReady'; +import { meMock, TEST_USER } from '../../test/authMocks'; import { WineCard } from './WineCard'; function StateProbe() { @@ -21,6 +24,15 @@ const wine: WineSummary = { students: { average: 4.56, count: 23 }, }; +/** The API's answer when the heart is clicked: the wine's lists afterwards. */ +const favourite = (myLists: string[]) => ({ + request: { + query: SET_WINE_IN_LIST_MUTATION, + variables: { wineId: wine.id, list: 'FAVOURITE', inList: true }, + }, + result: { data: { setWineInList: { __typename: 'Wine', id: wine.id, myLists } } }, +}); + describe('WineCard', () => { it('lenker til vinens detaljside via navnet', () => { renderWithRouter(); @@ -62,28 +74,67 @@ describe('WineCard', () => { expect(screen.getByText('Fellesskapet')).toBeInTheDocument(); }); - it('«Vil prøve» er en toggle-knapp med vinnavnet i navnet', async () => { - const { user } = renderWithRouter(); - const button = screen.getByRole('button', { name: 'Vil prøve Mosel Riesling Kabinett' }); - expect(button).toHaveAttribute('aria-pressed', 'false'); - await user.click(button); - expect(button).toHaveAttribute('aria-pressed', 'true'); - await user.click(button); - expect(button).toHaveAttribute('aria-pressed', 'false'); + it('har hjerte og bokmerke som toggle-knapper med vinnavnet i navnet', () => { + renderWithRouter(); + for (const name of ['Favoritt Mosel Riesling Kabinett', 'Vil prøve Mosel Riesling Kabinett']) { + expect(screen.getByRole('button', { name })).toHaveAttribute('aria-pressed', 'false'); + } }); - it('husker «Vil prøve» på tvers av kort med samme vin', async () => { + it('lagrer favoritten med en gang, og alle kort med samme vin viser det', async () => { const { user } = renderWithRouter( <> + , + { mocks: [meMock(TEST_USER), favourite(['FAVOURITE'])] }, ); - const [first, second] = screen.getAllByRole('button', { name: /Vil prøve/ }); + await screen.findByTestId('auth-ready'); + const [first, second] = screen.getAllByRole('button', { name: /^Favoritt/ }); + await user.click(first); + + expect(first).toHaveAttribute('aria-pressed', 'true'); expect(second).toHaveAttribute('aria-pressed', 'true'); }); + it('kan brukes med tastaturet: lenken, så hjertet og bokmerket', async () => { + const { user } = renderWithRouter( + <> + + + , + { mocks: [meMock(TEST_USER), favourite(['FAVOURITE'])] }, + ); + await screen.findByTestId('auth-ready'); + + await user.tab(); + expect(screen.getByRole('link', { name: 'Mosel Riesling Kabinett' })).toHaveFocus(); + await user.tab(); + const heart = screen.getByRole('button', { name: 'Favoritt Mosel Riesling Kabinett' }); + expect(heart).toHaveFocus(); + await user.keyboard(' '); + expect(heart).toHaveAttribute('aria-pressed', 'true'); + await user.tab(); + expect(screen.getByRole('button', { name: 'Vil prøve Mosel Riesling Kabinett' })).toHaveFocus(); + }); + + it('sender en besøkende til innlogging', async () => { + const { user } = renderWithRouter( + <> + + + , + { route: '/sok?q=riesling' }, + ); + await screen.findByTestId('auth-ready'); + + await user.click(screen.getByRole('button', { name: 'Vil prøve Mosel Riesling Kabinett' })); + + expect(screen.getByTestId('location')).toHaveTextContent('/konto'); + }); + it('har ingen axe-brudd', async () => { const { container } = renderWithRouter(); expect(await axe(container)).toHaveNoViolations(); diff --git a/frontend/src/components/ui/WineCard.tsx b/frontend/src/components/ui/WineCard.tsx index 190140b..3c464d3 100644 --- a/frontend/src/components/ui/WineCard.tsx +++ b/frontend/src/components/ui/WineCard.tsx @@ -1,10 +1,9 @@ import { Link, useLocation } from 'react-router'; -import { useWishlist } from '../../hooks/useWishlist'; +import { WineCardListButtons } from '../../features/lists/components/WineCardListButtons'; import { formatRatingSummary } from '../../lib/format'; import type { WineSummary } from '../../lib/types'; import { WINE_TYPES, wineTypeToken } from '../../lib/wineTypes'; import { Bottle } from './Bottle'; -import { HeartIcon } from './HeartIcon'; import styles from './WineCard.module.css'; interface WineCardProps { @@ -15,11 +14,10 @@ interface WineCardProps { /** * Vinkort brukt på forsiden og i søkeresultatet. - * Hele kortet er klikkbart via en utvidet lenke på navnet (én tabstopp - * for lenken + én for hjerteknappen), i stedet for en lenke rundt alt. + * Hele kortet er klikkbart via en utvidet lenke på navnet (én tabstopp for lenken, og én for + * hver av knappene for hjertet og bokmerket), i stedet for en lenke rundt alt. */ export function WineCard({ wine, headingLevel: Heading = 'h3' }: WineCardProps) { - const { isSaved, toggle } = useWishlist(wine.id); const typeMeta = WINE_TYPES[wine.type]; const { pathname, search } = useLocation(); @@ -59,15 +57,7 @@ export function WineCard({ wine, headingLevel: Heading = 'h3' }: WineCardProps) - + ); } diff --git a/frontend/src/features/landing/LandingPage.test.tsx b/frontend/src/features/landing/LandingPage.test.tsx index f2cf3bc..779b7f4 100644 --- a/frontend/src/features/landing/LandingPage.test.tsx +++ b/frontend/src/features/landing/LandingPage.test.tsx @@ -3,6 +3,8 @@ import { render, screen, within } from '@testing-library/react'; import { MockedProvider } from '@apollo/client/testing/react'; import { MemoryRouter } from 'react-router'; import { createApolloCache } from '../../lib/apollo'; +import { AuthProvider } from '../auth/AuthProvider'; +import { meMock } from '../../test/authMocks'; import { LANDING_QUERY } from './api/landingQuery'; import LandingPage from './LandingPage'; @@ -45,9 +47,12 @@ const mock = { describe('LandingPage', () => { it('shows data from the API and sets the page title', async () => { render( - + - + {/* The wine cards have list buttons, which need to know who is logged in. */} + + + , ); diff --git a/frontend/src/features/lists/api/listCache.test.ts b/frontend/src/features/lists/api/listCache.test.ts new file mode 100644 index 0000000..68ec28b --- /dev/null +++ b/frontend/src/features/lists/api/listCache.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, it } from 'vitest'; +import { gql } from '@apollo/client'; +import { createApolloCache } from '../../../lib/apollo'; +import type { WineListName } from '../../../lib/wineLists'; +import { updateListPages } from './listCache'; + +const LIST = gql` + query List($list: WineList!) { + me { + id + wines(list: $list) { + totalCount + edges { + cursor + node { + id + } + } + } + } + } +`; + +const TOP = gql` + query Top { + me { + id + topFavourites { + id + } + } + } +`; + +const wineRef = (id: string) => ({ __typename: 'Wine', id }); + +/** A cache with the user's lists as the API last sent them. */ +function cacheWith(lists: Partial>, top: string[] = []) { + const cache = createApolloCache(); + for (const [list, ids] of Object.entries(lists)) { + cache.writeQuery({ + query: LIST, + variables: { list }, + data: { + me: { + __typename: 'User', + id: '1', + wines: { + __typename: 'WineConnection', + totalCount: ids.length, + edges: ids.map((id) => ({ __typename: 'WineEdge', cursor: id, node: wineRef(id) })), + }, + }, + }, + }); + } + cache.writeQuery({ + query: TOP, + data: { me: { __typename: 'User', id: '1', topFavourites: top.map(wineRef) } }, + }); + return cache; +} + +type ListData = { me: { wines: { totalCount: number; edges: { node: { id: string } }[] } } }; + +/** The ids on a cached list and its count, or null when the list is no longer in the cache. */ +function read(cache: ReturnType, list: WineListName) { + const data = cache.readQuery({ query: LIST, variables: { list } }); + if (!data) return null; + return { + ids: data.me.wines.edges.map((edge) => edge.node.id), + totalCount: data.me.wines.totalCount, + }; +} + +const topOf = (cache: ReturnType) => + cache + .readQuery<{ me: { topFavourites: { id: string }[] } }>({ query: TOP }) + ?.me.topFavourites.map((wine) => wine.id); + +describe('updateListPages', () => { + it('takes the wine out of the lists it left, and counts one less', () => { + const cache = cacheWith({ WANT_TO_TRY: ['7', '8'], FAVOURITE: ['7'] }); + + updateListPages(cache, { + userId: '1', + wineId: '7', + before: ['FAVOURITE', 'WANT_TO_TRY'], + after: ['FAVOURITE', 'TRIED'], + }); + + expect(read(cache, 'WANT_TO_TRY')).toEqual({ ids: ['8'], totalCount: 1 }); + expect(read(cache, 'FAVOURITE')).toEqual({ ids: ['7'], totalCount: 1 }); + }); + + it('removes a list the wine joined, so it is fetched again with the wine at the top', () => { + const cache = cacheWith({ TRIED: ['8'], FAVOURITE: ['8'] }); + + updateListPages(cache, { userId: '1', wineId: '7', before: [], after: ['TRIED'] }); + + expect(read(cache, 'TRIED')).toBeNull(); + expect(read(cache, 'FAVOURITE')).toEqual({ ids: ['8'], totalCount: 1 }); + }); + + it('takes a wine out of the top 4 when it is no longer a favourite, and keeps the order', () => { + const cache = cacheWith({ FAVOURITE: ['7', '8', '9'] }, ['9', '7', '8']); + + updateListPages(cache, { userId: '1', wineId: '7', before: ['FAVOURITE'], after: [] }); + + expect(topOf(cache)).toEqual(['9', '8']); + expect(read(cache, 'FAVOURITE')).toEqual({ ids: ['8', '9'], totalCount: 2 }); + }); + + it('changes nothing when the lists are the same', () => { + const cache = cacheWith({ FAVOURITE: ['7'] }, ['7']); + + updateListPages(cache, { + userId: '1', + wineId: '7', + before: ['FAVOURITE'], + after: ['FAVOURITE'], + }); + + expect(read(cache, 'FAVOURITE')).toEqual({ ids: ['7'], totalCount: 1 }); + expect(topOf(cache)).toEqual(['7']); + }); +}); diff --git a/frontend/src/features/lists/api/listCache.ts b/frontend/src/features/lists/api/listCache.ts new file mode 100644 index 0000000..681f97e --- /dev/null +++ b/frontend/src/features/lists/api/listCache.ts @@ -0,0 +1,60 @@ +import type { ApolloCache, Reference } from '@apollo/client'; +import type { WineConnection } from '../../../lib/apollo'; +import type { WineListName } from '../../../lib/wineLists'; + +/** The list a cached `wines` field belongs to, from its key in the cache: wines:{"list":"TRIED"}. */ +function listOf(storeFieldName: string): string | null { + return /"list":"([A-Z_]+)"/.exec(storeFieldName)?.[1] ?? null; +} + +/** + * Keeps the user's list pages in the cache in step with a change of one wine's lists, so a page + * that shows them (such as «Mine anmeldelser») changes at once without a new request. + * + * - A list the wine left: the wine is taken out, and the count goes down by one. Also from the + * top 4 when it is no longer a favourite. + * - A list the wine joined: the new wine belongs at the top, with a cursor only the API can make. + * The cached list is removed instead, so it is fetched again the next time it is shown. + * + * Runs in the mutation's `update`, also for the optimistic answer, so a failed change is undone + * here too. + */ +export function updateListPages( + cache: ApolloCache, + { + userId, + wineId, + before, + after, + }: { userId: string; wineId: string; before: WineListName[]; after: WineListName[] }, +) { + const left = before.filter((list) => !after.includes(list)); + const joined = after.filter((list) => !before.includes(list)); + if (left.length === 0 && joined.length === 0) return; + + const id = cache.identify({ __typename: 'User', id: userId }); + if (!id) return; + + cache.modify({ + id, + fields: { + wines(value, { storeFieldName, readField, DELETE }) { + // The cache types a field as either a stored object or a reference to one. `wines` is + // always stored in place on the user (WineConnection has no id), so it is the object. + const existing = value as WineConnection; + const list = listOf(storeFieldName) as WineListName | null; + if (!list) return DELETE; // A key we cannot read: safest to fetch it again. + if (joined.includes(list)) return DELETE; + if (!left.includes(list)) return existing; + + const edges = existing.edges.filter((edge) => readField('id', edge.node) !== wineId); + if (edges.length === existing.edges.length) return existing; + return { ...existing, totalCount: existing.totalCount - 1, edges }; + }, + topFavourites(existing: readonly Reference[], { readField }) { + if (!left.includes('FAVOURITE')) return existing; + return existing.filter((wine) => readField('id', wine) !== wineId); + }, + }, + }); +} diff --git a/frontend/src/features/lists/api/listQueries.ts b/frontend/src/features/lists/api/listQueries.ts index 476297a..76d1429 100644 --- a/frontend/src/features/lists/api/listQueries.ts +++ b/frontend/src/features/lists/api/listQueries.ts @@ -26,3 +26,13 @@ export const SET_WINE_IN_LIST_MUTATION = gql` } } `; + +export interface SetWineInListData { + setWineInList: { __typename: 'Wine'; id: string; myLists: WineListName[] }; +} + +export interface SetWineInListVariables { + wineId: string; + list: WineListName; + inList: boolean; +} diff --git a/frontend/src/features/lists/api/myWineListQuery.ts b/frontend/src/features/lists/api/myWineListQuery.ts new file mode 100644 index 0000000..58b2bab --- /dev/null +++ b/frontend/src/features/lists/api/myWineListQuery.ts @@ -0,0 +1,48 @@ +import { gql } from '@apollo/client'; +import type { ApiWine } from '../../../lib/mapWine'; + +/** + * One page of one of the logged-in user's lists, newest first. The wine fields are the same as + * on the wine cards, with `myLists`, so the buttons on the cards know their state. + */ +export const MY_WINE_LIST_QUERY = gql` + query MyWineList($list: WineList!, $first: Int, $after: String) { + me { + id + wines(list: $list, first: $first, after: $after) { + totalCount + edges { + cursor + node { + id + name + type + grapes + country + countryCode + wineryName + communityRating + communityRatingCount + myLists + } + } + pageInfo { + hasNextPage + endCursor + } + } + } + } +`; + +export interface MyWineListData { + /** null when the session has ended. */ + me: { + id: string; + wines: { + totalCount: number; + edges: { cursor: string; node: ApiWine }[]; + pageInfo: { hasNextPage: boolean; endCursor: string | null }; + }; + } | null; +} diff --git a/frontend/src/features/lists/api/useMyWineList.ts b/frontend/src/features/lists/api/useMyWineList.ts new file mode 100644 index 0000000..50ebc7e --- /dev/null +++ b/frontend/src/features/lists/api/useMyWineList.ts @@ -0,0 +1,71 @@ +import { useRef, useState } from 'react'; +import { NetworkStatus } from '@apollo/client'; +import { useQuery } from '@apollo/client/react'; +import { toWineSummary } from '../../../lib/mapWine'; +import type { WineSummary } from '../../../lib/types'; +import type { WineListName } from '../../../lib/wineLists'; +import { MY_WINE_LIST_QUERY, type MyWineListData } from './myWineListQuery'; + +/** How many wines one page of a list has: the same as a page of search results. */ +export const LIST_PAGE_SIZE = 24; + +export interface MyWineListResult { + wines: WineSummary[]; + /** How many wines the whole list has, also those not loaded yet. Undefined until loaded. */ + totalCount: number | undefined; + /** The first page is on its way. */ + loading: boolean; + loadingMore: boolean; + hasNextPage: boolean; + error: Error | undefined; + loadMoreError: Error | undefined; + loadMore: () => Promise; + refetch: () => void; +} + +/** + * The logged-in user's wines on one list, newest first, one page at a time. The pages are kept + * together in the cache (User.wines in lib/apollo.ts), and a change made with the list buttons + * updates them at once (updateListPages). + */ +export function useMyWineList(list: WineListName): MyWineListResult { + const { data, error, networkStatus, fetchMore, refetch } = useQuery( + MY_WINE_LIST_QUERY, + { variables: { list, first: LIST_PAGE_SIZE } }, + ); + const isFetchingMore = useRef(false); + const [loadMoreError, setLoadMoreError] = useState(); + + const connection = data?.me?.wines; + const loadingMore = networkStatus === NetworkStatus.fetchMore; + + async function loadMore() { + const after = connection?.pageInfo.endCursor; + if (!connection?.pageInfo.hasNextPage || !after || isFetchingMore.current) return; + + isFetchingMore.current = true; + try { + await fetchMore({ variables: { after } }); + setLoadMoreError(undefined); + } catch (cause) { + // The pages already loaded stay. The page offers to try the next one again. + setLoadMoreError(cause instanceof Error ? cause : new Error(String(cause))); + } finally { + isFetchingMore.current = false; + } + } + + return { + wines: (connection?.edges ?? []) + .map(({ node }) => toWineSummary(node)) + .filter((wine): wine is WineSummary => wine !== null), + totalCount: connection?.totalCount, + loading: networkStatus === NetworkStatus.loading, + loadingMore, + hasNextPage: Boolean(connection?.pageInfo.hasNextPage), + error, + loadMoreError, + loadMore, + refetch: () => void refetch().catch(() => undefined), + }; +} diff --git a/frontend/src/features/lists/components/WineCardListButtons.module.css b/frontend/src/features/lists/components/WineCardListButtons.module.css new file mode 100644 index 0000000..5796c0e --- /dev/null +++ b/frontend/src/features/lists/components/WineCardListButtons.module.css @@ -0,0 +1,56 @@ +/* In the top right corner of the card, over the link that covers the whole card. */ +.actions { + position: absolute; + z-index: 1; + top: var(--space-2); + right: var(--space-2); + display: grid; + gap: var(--space-1); +} + +.button { + display: grid; + place-items: center; + width: var(--tap-target); + height: var(--tap-target); + padding: 0; + border: 0; + border-radius: 50%; + background: transparent; + cursor: pointer; +} + +.button svg { + width: 1.4rem; + height: 1.4rem; + fill: none; + stroke: var(--color-brand); + stroke-width: 2; + stroke-linejoin: round; + transition: fill var(--transition); +} + +.button:hover { + background: var(--color-surface-muted); +} + +.button[aria-pressed='true'] svg { + fill: var(--color-brand); +} + +/* Below the card's content, across both columns. */ +.error { + grid-column: 1 / -1; + 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/WineCardListButtons.tsx b/frontend/src/features/lists/components/WineCardListButtons.tsx new file mode 100644 index 0000000..714a316 --- /dev/null +++ b/frontend/src/features/lists/components/WineCardListButtons.tsx @@ -0,0 +1,52 @@ +import { useWineList } from '../useWineList'; +import { LIST_BUTTONS } from './listButtons'; +import styles from './WineCardListButtons.module.css'; + +const ON_CARD = ['FAVOURITE', 'WANT_TO_TRY'] as const; + +interface WineCardListButtonsProps { + wineId: string; + /** In the accessible name, so «Favoritt Origem Merlot» says which of the cards it belongs to. */ + wineName: string; +} + +/** + * The heart and the bookmark in the corner of a wine card. Icons only, to keep the cards calm, so + * each button has an aria-label with the wine's name. «Har prøvd» is on the wine page, where + * the user has read about the wine. + */ +export function WineCardListButtons({ wineId, wineName }: WineCardListButtonsProps) { + const favourite = useWineList(wineId, 'FAVOURITE'); + const wantToTry = useWineList(wineId, 'WANT_TO_TRY'); + const states = { FAVOURITE: favourite, WANT_TO_TRY: wantToTry }; + const error = favourite.error ?? wantToTry.error; + + 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/useWineList.test.tsx b/frontend/src/features/lists/useWineList.test.tsx index 0b4efec..7be5e38 100644 --- a/frontend/src/features/lists/useWineList.test.tsx +++ b/frontend/src/features/lists/useWineList.test.tsx @@ -167,7 +167,7 @@ describe('useWineList', () => { expect(button('WANT_TO_TRY')).toHaveAttribute('aria-pressed', 'true'); }); - it('removes the user’s list pages from the cache, so they are fetched again', async () => { + 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'], }); @@ -177,6 +177,12 @@ describe('useWineList', () => { id wines(list: FAVOURITE) { totalCount + edges { + cursor + node { + id + } + } } } } @@ -187,7 +193,13 @@ describe('useWineList', () => { me: { __typename: 'User', id: USER.id, - wines: { __typename: 'WineConnection', totalCount: 1 }, + wines: { + __typename: 'WineConnection', + totalCount: 1, + edges: [ + { __typename: 'WineEdge', cursor: 'c', node: { __typename: 'Wine', id: WINE_ID } }, + ], + }, }, }, }); @@ -195,7 +207,16 @@ describe('useWineList', () => { await user.click(button('FAVOURITE')); - await waitFor(() => expect(cache.readQuery({ query: LIST })).toBeNull()); + // 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 () => { diff --git a/frontend/src/features/lists/useWineList.ts b/frontend/src/features/lists/useWineList.ts index c800b78..665209b 100644 --- a/frontend/src/features/lists/useWineList.ts +++ b/frontend/src/features/lists/useWineList.ts @@ -1,12 +1,15 @@ import { useRef, useState } from 'react'; -import { useApolloClient, useFragment, useMutation } from '@apollo/client/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'; @@ -29,14 +32,15 @@ export interface WineListState { */ export function useWineList(wineId: string, list: WineListName): WineListState { const { user, loading: checkingLogin } = useAuth(); - const client = useApolloClient(); const navigate = useNavigate(); const location = useLocation(); const [error, setError] = useState(null); // One change at a time: a second click while the first is on its way is ignored, so two // requests can never arrive in the wrong order and leave the list the wrong way round. const pending = useRef(false); - const [setWineInList] = useMutation(SET_WINE_IN_LIST_MUTATION); + const [setWineInList] = useMutation( + SET_WINE_IN_LIST_MUTATION, + ); const { data } = useFragment({ fragment: WINE_LISTS_FRAGMENT, @@ -67,13 +71,12 @@ export function useWineList(wineId: string, list: WineListName): WineListState { 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 }); + }, }); - // The pages that list the user's wines (and the top 4) no longer match. Removing them from - // the cache makes a page that shows them fetch them again, and the others when next shown. - const userId = client.cache.identify({ __typename: 'User', id: user.id }); - client.cache.evict({ id: userId, fieldName: 'wines' }); - client.cache.evict({ id: userId, fieldName: 'topFavourites' }); - client.cache.gc(); } catch (failure) { setError(`Vi fikk ikke lagret endringen. ${ERROR_DETAILS[classifyError(failure)]}`); } finally { diff --git a/frontend/src/features/my/MyPage.test.tsx b/frontend/src/features/my/MyPage.test.tsx index 14f6cf8..c15addf 100644 --- a/frontend/src/features/my/MyPage.test.tsx +++ b/frontend/src/features/my/MyPage.test.tsx @@ -1,92 +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: [], + 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, @@ -95,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'), }, @@ -112,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 e84f404..0000000 --- a/frontend/src/features/my/api/wishlistQuery.ts +++ /dev/null @@ -1,54 +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 - myLists - }`, - ) - .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/wine/components/SimilarWines.test.tsx b/frontend/src/features/wine/components/SimilarWines.test.tsx index 33c28a9..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'; @@ -68,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 67b5f72..1c50258 100644 --- a/frontend/src/lib/apollo.test.ts +++ b/frontend/src/lib/apollo.test.ts @@ -68,6 +68,66 @@ describe('createApolloCache', () => { }); }); +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 { diff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.ts index dc22500..ac176ec 100644 --- a/frontend/src/lib/apollo.ts +++ b/frontend/src/lib/apollo.ts @@ -33,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: { 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 }; } From bff08e9552d229536bd4548ee0ca8b06c90bcd39 Mon Sep 17 00:00:00 2001 From: Magnus Andreas Igesund Nerland Date: Thu, 19 Nov 2026 15:13:58 +0100 Subject: [PATCH 5/8] =?UTF-8?q?feat(frontend):=20move=20a=20=C2=ABVil=20pr?= =?UTF-8?q?=C3=B8ve=C2=BB=20list=20from=20before=20login=20to=20the=20user?= =?UTF-8?q?,=20once=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/src/components/layout/AppLayout.tsx | 3 + .../src/features/lists/legacyWishlist.test.ts | 97 +++++++++++++++++++ frontend/src/features/lists/legacyWishlist.ts | 71 ++++++++++++++ .../lists/useLegacyWishlistImport.test.tsx | 62 ++++++++++++ .../features/lists/useLegacyWishlistImport.ts | 28 ++++++ 5 files changed, 261 insertions(+) create mode 100644 frontend/src/features/lists/legacyWishlist.test.ts create mode 100644 frontend/src/features/lists/legacyWishlist.ts create mode 100644 frontend/src/features/lists/useLegacyWishlistImport.test.tsx create mode 100644 frontend/src/features/lists/useLegacyWishlistImport.ts 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/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]); +} From 3e7b5201793def0be26911a5cd931a7cbd90e36e Mon Sep 17 00:00:00 2001 From: Magnus Andreas Igesund Nerland Date: Thu, 19 Nov 2026 15:23:45 +0100 Subject: [PATCH 6/8] =?UTF-8?q?test(e2e):=20wine=20lists,=20login=20on=20t?= =?UTF-8?q?he=20way,=20and=20the=20move=20of=20an=20old=20=C2=ABVil=20pr?= =?UTF-8?q?=C3=B8ve=C2=BB=20list=20(#72)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- frontend/e2e/lists.spec.ts | 207 +++++++++++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 frontend/e2e/lists.spec.ts 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); + }); +}); From 5a01b98c747316389a508acf06d21e04aa2b3df2 Mon Sep 17 00:00:00 2001 From: Magnus Andreas Igesund Nerland Date: Thu, 19 Nov 2026 15:36:51 +0100 Subject: [PATCH 7/8] docs: wine lists in the interface, and manual tests for them (#72) --- README.md | 23 +++++++++++++---------- docs/api.md | 24 ++++++++++++++++++++++++ docs/manual-testing.md | 32 +++++++++++++++++++++++++++----- 3 files changed, 64 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 23d718c..d759a9e 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 | @@ -126,8 +126,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 +160,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 +238,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 +301,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 +395,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 +410,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/docs/api.md b/docs/api.md index 7e8e404..db186d4 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 @@ -275,6 +281,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`**, 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 | |---|---| From d2cad34f1c46dfb0d1331a28fdff0f749864d545 Mon Sep 17 00:00:00 2001 From: Magnus Andreas Igesund Nerland Date: Thu, 19 Nov 2026 15:52:34 +0100 Subject: [PATCH 8/8] docs: answers to the review of #71: one-way rule, demo user reset, migrating the test database (#72) --- README.md | 11 ++++++++--- backend/src/lists/lists-api.db.test.ts | 12 ++++++++++++ docs/api.md | 15 ++++++++++++++- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d759a9e..674a0fd 100644 --- a/README.md +++ b/README.md @@ -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 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 db186d4..902791d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -233,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')` | @@ -323,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 @@ -330,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.