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 (
} />
-
-
+
+
+ } />
+ 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 `