+ );
+}
diff --git a/frontend/src/features/search/api/searchQuery.ts b/frontend/src/features/search/api/searchQuery.ts
new file mode 100644
index 0000000..449a024
--- /dev/null
+++ b/frontend/src/features/search/api/searchQuery.ts
@@ -0,0 +1,33 @@
+import { gql } from '@apollo/client';
+
+/** One page of wines. Search, filtering and sorting run in the database. */
+export const SEARCH_WINES_QUERY = gql`
+ query SearchWines(
+ $search: String
+ $filter: WineFilter
+ $sort: WineSort
+ $first: Int
+ $after: String
+ ) {
+ wines(search: $search, filter: $filter, sort: $sort, first: $first, after: $after) {
+ totalCount
+ edges {
+ cursor
+ node {
+ id
+ name
+ type
+ grapes
+ country
+ wineryName
+ communityRating
+ communityRatingCount
+ }
+ }
+ pageInfo {
+ hasNextPage
+ endCursor
+ }
+ }
+ }
+`;
diff --git a/frontend/src/features/search/api/searchVariables.test.ts b/frontend/src/features/search/api/searchVariables.test.ts
new file mode 100644
index 0000000..58cd74e
--- /dev/null
+++ b/frontend/src/features/search/api/searchVariables.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+import { PAGE_SIZE, toSearchVariables } from './searchVariables';
+
+describe('toSearchVariables', () => {
+ it('browses the whole catalogue for an empty search', () => {
+ expect(toSearchVariables({})).toEqual({ sort: 'TOP_RATED', first: PAGE_SIZE });
+ });
+
+ it('sends the search text', () => {
+ expect(toSearchVariables({ q: 'pinot' }).search).toBe('pinot');
+ });
+
+ it('translates the URL filters to the API filter', () => {
+ expect(
+ toSearchVariables({ type: 'FORTIFIED', country: 'IT', grape: 'Riesling', food: 'Pizza' })
+ .filter,
+ ).toEqual({
+ types: ['Dessert/Port'],
+ countryCodes: ['IT'],
+ grapes: ['Riesling'],
+ harmonize: ['Pizza'],
+ });
+ });
+
+ it('only sends the filters that are set', () => {
+ expect(toSearchVariables({ type: 'RED' }).filter).toEqual({ types: ['Red'] });
+ });
+
+ it.each([
+ ['relevance', 'TOP_RATED'],
+ ['rating', 'TOP_RATED'],
+ ['reviews', 'MOST_RATED'],
+ ['name', 'NAME_ASC'],
+ ] as const)('maps sort %s to %s', (sort, expected) => {
+ expect(toSearchVariables({ sort }).sort).toBe(expected);
+ });
+});
diff --git a/frontend/src/features/search/api/searchVariables.ts b/frontend/src/features/search/api/searchVariables.ts
new file mode 100644
index 0000000..acc6a72
--- /dev/null
+++ b/frontend/src/features/search/api/searchVariables.ts
@@ -0,0 +1,52 @@
+import { toApiWineType } from '../../../lib/mapWine';
+import type { SearchState, SortOption } from '../../../lib/searchParams';
+
+/** Number of wines per "Last inn flere". */
+export const PAGE_SIZE = 24;
+
+type ApiSort = 'TOP_RATED' | 'MOST_RATED' | 'NAME_ASC';
+
+/** The API has no relevance ranking yet, so the default order is the top rated wines. */
+const API_SORT: Record = {
+ relevance: 'TOP_RATED',
+ rating: 'TOP_RATED',
+ reviews: 'MOST_RATED',
+ name: 'NAME_ASC',
+};
+
+export interface SearchVariables {
+ search?: string;
+ filter?: {
+ types?: string[];
+ countryCodes?: string[];
+ grapes?: string[];
+ harmonize?: string[];
+ };
+ sort: ApiSort;
+ first: number;
+ after?: string;
+}
+
+/** Translates the search state from the URL to variables for SEARCH_WINES_QUERY. */
+export function toSearchVariables({
+ q,
+ type,
+ country,
+ grape,
+ food,
+ sort = 'relevance',
+}: SearchState): SearchVariables {
+ const filter = {
+ ...(type && { types: [toApiWineType(type)] }),
+ ...(country && { countryCodes: [country] }),
+ ...(grape && { grapes: [grape] }),
+ ...(food && { harmonize: [food] }),
+ };
+
+ return {
+ ...(q && { search: q }),
+ ...(Object.keys(filter).length > 0 && { filter }),
+ sort: API_SORT[sort],
+ first: PAGE_SIZE,
+ };
+}
diff --git a/frontend/src/features/search/api/useWineSearch.test.tsx b/frontend/src/features/search/api/useWineSearch.test.tsx
new file mode 100644
index 0000000..3afa64b
--- /dev/null
+++ b/frontend/src/features/search/api/useWineSearch.test.tsx
@@ -0,0 +1,168 @@
+import type { ReactNode } from 'react';
+import { describe, expect, it } from 'vitest';
+import { act, renderHook, 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 type { SearchState } from '../../../lib/searchParams';
+import { searchMock, winesPage } from '../../../test/searchMocks';
+import { SEARCH_WINES_QUERY } from './searchQuery';
+import { useWineSearch } from './useWineSearch';
+
+function renderSearch(mocks: MockLink.MockedResponse[], initial: SearchState = { q: 'pinot' }) {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+
+ {children}
+
+ );
+ return renderHook((state: SearchState) => useWineSearch(state), {
+ wrapper,
+ initialProps: initial,
+ });
+}
+
+const failing = (message: string, after?: string): MockLink.MockedResponse => ({
+ request: {
+ query: SEARCH_WINES_QUERY,
+ variables: (variables) => variables.after === after,
+ },
+ error: new Error(message),
+});
+
+const page = (total: number, after?: string): MockLink.MockedResponse => ({
+ request: {
+ query: SEARCH_WINES_QUERY,
+ variables: (variables) => variables.after === after,
+ },
+ result: winesPage(total, 2, after),
+});
+
+describe('useWineSearch', () => {
+ it('starts loading and then gives wines and the number of hits', async () => {
+ const { result } = renderSearch([searchMock(() => 5).mock]);
+
+ expect(result.current.loading).toBe(true);
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ expect(result.current.wines.map((wine) => wine.name)).toEqual(['Vin 1', 'Vin 2']);
+ expect(result.current.totalCount).toBe(5);
+ expect(result.current.hasNextPage).toBe(true);
+ });
+
+ it('adds the next page without counting as a new search', async () => {
+ const { result } = renderSearch([searchMock(() => 3).mock]);
+ await waitFor(() => expect(result.current.wines).toHaveLength(2));
+
+ await act(() => result.current.loadMore());
+
+ await waitFor(() => expect(result.current.wines).toHaveLength(3));
+ expect(result.current.hasNextPage).toBe(false);
+ expect(result.current.loading).toBe(false);
+ });
+
+ it('sends one request when load more is called twice in a row', async () => {
+ const { mock, resolver } = searchMock(() => 5);
+ const { result } = renderSearch([mock]);
+ await waitFor(() => expect(result.current.wines).toHaveLength(2));
+ resolver.mockClear();
+
+ await act(async () => {
+ await Promise.all([result.current.loadMore(), result.current.loadMore()]);
+ });
+
+ await waitFor(() => expect(result.current.wines).toHaveLength(4));
+ expect(resolver).toHaveBeenCalledOnce();
+ });
+
+ it('does nothing when there are no more pages', async () => {
+ const { mock, resolver } = searchMock(() => 2);
+ const { result } = renderSearch([mock]);
+ await waitFor(() => expect(result.current.wines).toHaveLength(2));
+ resolver.mockClear();
+
+ await act(() => result.current.loadMore());
+
+ expect(resolver).not.toHaveBeenCalled();
+ });
+
+ it('starts from the first page for a new search', async () => {
+ const { mock } = searchMock(({ search }) => (search === 'pinot' ? 3 : 1));
+ const { result, rerender } = renderSearch([mock]);
+ await waitFor(() => expect(result.current.wines).toHaveLength(2));
+ await act(() => result.current.loadMore());
+ await waitFor(() => expect(result.current.wines).toHaveLength(3));
+
+ rerender({ q: 'merlot' });
+
+ await waitFor(() => expect(result.current.totalCount).toBe(1));
+ expect(result.current.wines).toHaveLength(1);
+ });
+
+ it('keeps the old wines visible while a new search loads', async () => {
+ const { mock } = searchMock(() => 2);
+ const { result, rerender } = renderSearch([mock]);
+ await waitFor(() => expect(result.current.wines).toHaveLength(2));
+
+ rerender({ q: 'merlot' });
+
+ expect(result.current.loading).toBe(true);
+ expect(result.current.wines).toHaveLength(2);
+ });
+
+ it('uses the cache when the user returns to an earlier search', async () => {
+ const { mock, resolver } = searchMock(() => 2);
+ const { result, rerender } = renderSearch([mock]);
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ rerender({ q: 'merlot' });
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ resolver.mockClear();
+
+ rerender({ q: 'pinot' });
+
+ await waitFor(() => expect(result.current.loading).toBe(false));
+ expect(resolver).not.toHaveBeenCalled();
+ });
+
+ it('gives an error when the search fails, and refetch tries again', async () => {
+ const { result } = renderSearch([failing('Network error'), page(1)]);
+
+ await waitFor(() => expect(result.current.error?.message).toBe('Network error'));
+ expect(result.current.wines).toEqual([]);
+
+ act(() => result.current.refetch());
+
+ await waitFor(() => expect(result.current.wines).toHaveLength(1));
+ expect(result.current.error).toBeUndefined();
+ });
+
+ it('keeps the wines when load more fails, and can try again', async () => {
+ const { result } = renderSearch([page(3), failing('Load failed', '2'), page(3, '2')]);
+ await waitFor(() => expect(result.current.wines).toHaveLength(2));
+
+ await act(() => result.current.loadMore());
+
+ expect(result.current.loadMoreError?.message).toBe('Load failed');
+ expect(result.current.error).toBeUndefined();
+ expect(result.current.wines).toHaveLength(2);
+
+ await act(() => result.current.loadMore());
+
+ await waitFor(() => expect(result.current.wines).toHaveLength(3));
+ expect(result.current.loadMoreError).toBeUndefined();
+ });
+
+ it('forgets a load more error when the user searches for something else', async () => {
+ const { result, rerender } = renderSearch([
+ page(3),
+ failing('Load failed', '2'),
+ searchMock(() => 3).mock,
+ ]);
+ await waitFor(() => expect(result.current.wines).toHaveLength(2));
+ await act(() => result.current.loadMore());
+ expect(result.current.loadMoreError).toBeDefined();
+
+ rerender({ q: 'merlot' });
+
+ expect(result.current.loadMoreError).toBeUndefined();
+ });
+});
diff --git a/frontend/src/features/search/api/useWineSearch.ts b/frontend/src/features/search/api/useWineSearch.ts
new file mode 100644
index 0000000..891b83d
--- /dev/null
+++ b/frontend/src/features/search/api/useWineSearch.ts
@@ -0,0 +1,82 @@
+import { useRef, useState } from 'react';
+import { NetworkStatus } from '@apollo/client';
+import { useQuery } from '@apollo/client/react';
+import { toWineSummary, type ApiWine } from '../../../lib/mapWine';
+import type { SearchState } from '../../../lib/searchParams';
+import type { WineSummary } from '../../../lib/types';
+import { SEARCH_WINES_QUERY } from './searchQuery';
+import { toSearchVariables, type SearchVariables } from './searchVariables';
+
+interface SearchQueryData {
+ wines: {
+ totalCount: number;
+ edges: { cursor: string; node: ApiWine }[];
+ pageInfo: { hasNextPage: boolean; endCursor: string | null };
+ };
+}
+
+export interface WineSearchResult {
+ wines: WineSummary[];
+ /** Number of hits across all pages. Undefined until the first response. */
+ totalCount: number | undefined;
+ /** A new search is on its way. The previous wines stay in `wines` until it arrives. */
+ loading: boolean;
+ loadingMore: boolean;
+ error: Error | undefined;
+ loadMoreError: Error | undefined;
+ hasNextPage: boolean;
+ loadMore: () => Promise;
+ refetch: () => void;
+}
+
+/** Searches the catalogue and loads more pages. The list itself lives in the Apollo cache. */
+export function useWineSearch(state: SearchState): WineSearchResult {
+ const variables = toSearchVariables(state);
+ const { data, previousData, loading, error, networkStatus, fetchMore, refetch } = useQuery<
+ SearchQueryData,
+ SearchVariables
+ >(SEARCH_WINES_QUERY, { variables });
+
+ // A ref, because two quick clicks can both run before React renders again.
+ const isFetchingMore = useRef(false);
+ const [failedLoad, setFailedLoad] = useState<{ searchKey: string; error: Error }>();
+
+ const searchKey = JSON.stringify(variables);
+ const loadingMore = networkStatus === NetworkStatus.fetchMore;
+ const newSearchLoading = loading && !loadingMore;
+ const connection = (data ?? (error ? undefined : previousData))?.wines;
+ const hasNextPage = !newSearchLoading && Boolean(connection?.pageInfo.hasNextPage);
+
+ async function loadMore() {
+ const after = connection?.pageInfo.endCursor;
+ if (!hasNextPage || !after || isFetchingMore.current) return;
+
+ isFetchingMore.current = true;
+ try {
+ await fetchMore({ variables: { after } });
+ setFailedLoad(undefined);
+ } catch (cause) {
+ setFailedLoad({
+ searchKey,
+ error: 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: newSearchLoading,
+ loadingMore,
+ error,
+ loadMoreError: failedLoad?.searchKey === searchKey ? failedLoad.error : undefined,
+ hasNextPage,
+ loadMore,
+ // A failed retry already shows up in `error`, so the rejected promise needs no handling.
+ refetch: () => void refetch().catch(() => undefined),
+ };
+}
diff --git a/frontend/src/features/search/useSearchText.ts b/frontend/src/features/search/useSearchText.ts
new file mode 100644
index 0000000..0c90218
--- /dev/null
+++ b/frontend/src/features/search/useSearchText.ts
@@ -0,0 +1,41 @@
+import { useEffect, useState } from 'react';
+import { useSearchParams } from 'react-router';
+import { parseSearchParams, toSearchParams } from '../../lib/searchParams';
+
+const DEBOUNCE_MS = 300;
+
+const normalize = (text: string) => text.trim().replace(/\s+/g, ' ');
+
+/**
+ * The text in the search field. The URL is the source of truth for the search, so the
+ * field has its own state only for what the user is typing right now. The URL is updated
+ * when the user pauses, which keeps the number of requests down. `replace` means the
+ * back button leaves the search page instead of stepping through every word.
+ */
+export function useSearchText() {
+ const [params, setParams] = useSearchParams();
+ const urlText = parseSearchParams(params).q ?? '';
+ const [text, setText] = useState(urlText);
+ const [lastUrlText, setLastUrlText] = useState(urlText);
+
+ // The URL changed, for example with the back button. The check keeps a
+ // trailing space while the user is on the way to the next word.
+ if (urlText !== lastUrlText) {
+ setLastUrlText(urlText);
+ if (normalize(text) !== urlText) setText(urlText);
+ }
+
+ function search(value: string) {
+ setParams(toSearchParams({ ...parseSearchParams(params), q: value }), { replace: true });
+ }
+
+ useEffect(() => {
+ if (normalize(text) === urlText) return;
+ const timer = setTimeout(() => {
+ setParams(toSearchParams({ ...parseSearchParams(params), q: text }), { replace: true });
+ }, DEBOUNCE_MS);
+ return () => clearTimeout(timer);
+ }, [text, urlText, params, setParams]);
+
+ return { text, setText, submit: () => search(text) };
+}
diff --git a/frontend/src/lib/apollo.test.ts b/frontend/src/lib/apollo.test.ts
new file mode 100644
index 0000000..539e670
--- /dev/null
+++ b/frontend/src/lib/apollo.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+import { gql } from '@apollo/client';
+import { createApolloCache, mergeWineConnection, type WineConnection } from './apollo';
+
+const connection = (ids: string[], hasNextPage = true): WineConnection => ({
+ totalCount: 10,
+ edges: ids.map((id) => ({ cursor: `cursor-${id}`, node: { __ref: `Wine:${id}` } })),
+ pageInfo: { hasNextPage, endCursor: `cursor-${ids.at(-1)}` },
+});
+
+const ids = (result: WineConnection) => result.edges.map((edge) => edge.node.__ref);
+
+describe('mergeWineConnection', () => {
+ it('uses the incoming page when there is no existing data', () => {
+ const incoming = connection(['1', '2']);
+ expect(mergeWineConnection(undefined, incoming, undefined)).toBe(incoming);
+ });
+
+ it('replaces the list when the first page is fetched again', () => {
+ const result = mergeWineConnection(connection(['1', '2']), connection(['3']), undefined);
+ expect(ids(result)).toEqual(['Wine:3']);
+ });
+
+ it('adds the next page after the existing wines', () => {
+ const result = mergeWineConnection(connection(['1']), connection(['2'], false), 'cursor-1');
+ expect(ids(result)).toEqual(['Wine:1', 'Wine:2']);
+ });
+
+ it('uses the page info from the newest page', () => {
+ const result = mergeWineConnection(connection(['1']), connection(['2'], false), 'cursor-1');
+ expect(result.pageInfo).toEqual({ hasNextPage: false, endCursor: 'cursor-2' });
+ });
+
+ it('leaves out wines that are already in the list when the data has shifted', () => {
+ const result = mergeWineConnection(connection(['1', '2']), connection(['2', '3']), 'cursor-2');
+ expect(ids(result)).toEqual(['Wine:1', 'Wine:2', 'Wine:3']);
+ });
+});
+
+describe('createApolloCache', () => {
+ const write = (cache: ReturnType, first: number) =>
+ cache.writeQuery({
+ query: gql`
+ query Wines($first: Int) {
+ wines(first: $first) {
+ totalCount
+ }
+ }
+ `,
+ variables: { first },
+ data: { wines: { __typename: 'WineConnection', totalCount: first } },
+ });
+
+ it('keeps lists with different page sizes apart, so the landing page stays at six wines', () => {
+ const cache = createApolloCache();
+ write(cache, 6);
+ write(cache, 24);
+ const keys = Object.keys(cache.extract().ROOT_QUERY ?? {}).filter((key) =>
+ key.startsWith('wines'),
+ );
+ expect(keys).toHaveLength(2);
+ });
+});
diff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.ts
index 3e92b94..523b4be 100644
--- a/frontend/src/lib/apollo.ts
+++ b/frontend/src/lib/apollo.ts
@@ -1,7 +1,52 @@
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
+/** A page of the `wines` field as it is stored in the Apollo cache. */
+export interface WineConnection {
+ totalCount: number;
+ edges: { cursor: string; node: { __ref: string } }[];
+ pageInfo: { hasNextPage: boolean; endCursor: string | null };
+}
+
+/**
+ * Adds a new page to the wines already in the cache. Without `after` this is
+ * a first page, which replaces the list. A wine can move to the next page when
+ * the data changes between two requests, so wines already in the list are skipped.
+ */
+export function mergeWineConnection(
+ existing: WineConnection | undefined,
+ incoming: WineConnection,
+ after: string | null | undefined,
+): WineConnection {
+ if (!existing || !after) return incoming;
+
+ const seen = new Set(existing.edges.map((edge) => edge.node.__ref));
+ return {
+ ...incoming,
+ edges: [...existing.edges, ...incoming.edges.filter((edge) => !seen.has(edge.node.__ref))],
+ };
+}
+
+export function createApolloCache() {
+ return new InMemoryCache({
+ typePolicies: {
+ Query: {
+ fields: {
+ wines: {
+ // `after` is left out so all pages of a search share one list. `first` is
+ // included so the six wines on the landing page never mix with a search.
+ keyArgs: ['search', 'filter', 'sort', 'first'],
+ merge(existing: WineConnection | undefined, incoming: WineConnection, { args }) {
+ return mergeWineConnection(existing, incoming, args?.after as string | undefined);
+ },
+ },
+ },
+ },
+ },
+ });
+}
+
/** 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` }),
- cache: new InMemoryCache(),
+ cache: createApolloCache(),
});
diff --git a/frontend/src/lib/mapWine.test.ts b/frontend/src/lib/mapWine.test.ts
index 0317508..5b0a579 100644
--- a/frontend/src/lib/mapWine.test.ts
+++ b/frontend/src/lib/mapWine.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { toWineSummary, toWineType, type ApiWine } from './mapWine';
+import { toApiWineType, toWineSummary, toWineType, type ApiWine } from './mapWine';
const apiWine: ApiWine = {
id: '181199',
@@ -29,6 +29,16 @@ describe('toWineType', () => {
});
});
+describe('toApiWineType', () => {
+ it.each([
+ ['RED', 'Red'],
+ ['ROSE', 'Rosé'],
+ ['FORTIFIED', 'Dessert/Port'],
+ ] as const)('maps %s back to %s', (type, expected) => {
+ expect(toApiWineType(type)).toBe(expected);
+ });
+});
+
describe('toWineSummary', () => {
it('maps the API fields to the shape the wine card uses', () => {
expect(toWineSummary(apiWine)).toEqual({
diff --git a/frontend/src/lib/mapWine.ts b/frontend/src/lib/mapWine.ts
index 9e08eb1..6c9c051 100644
--- a/frontend/src/lib/mapWine.ts
+++ b/frontend/src/lib/mapWine.ts
@@ -26,6 +26,11 @@ export function toWineType(apiType: string): WineType | null {
return WINE_TYPE_BY_API_NAME[apiType] ?? null;
}
+export function toApiWineType(type: WineType): string {
+ const entry = Object.entries(WINE_TYPE_BY_API_NAME).find(([, wineType]) => wineType === type);
+ return entry ? entry[0] : type;
+}
+
/**
* Converts a wine from the API to the shape the components use.
* Returns null for an unknown type, because the card cannot show a wine without one.
diff --git a/frontend/src/test/searchMocks.ts b/frontend/src/test/searchMocks.ts
new file mode 100644
index 0000000..98e0bd9
--- /dev/null
+++ b/frontend/src/test/searchMocks.ts
@@ -0,0 +1,61 @@
+import { vi } from 'vitest';
+import type { MockLink } from '@apollo/client/testing';
+import type { ApiWine } from '../lib/mapWine';
+import { SEARCH_WINES_QUERY } from '../features/search/api/searchQuery';
+
+/** Variables a test can read back to see what was sent to the API. */
+export interface SentVariables {
+ search?: string;
+ after?: string;
+ filter?: { types?: string[] };
+}
+
+const wine = (id: number): ApiWine & { __typename: string } => ({
+ __typename: 'Wine',
+ id: String(id),
+ name: `Vin ${id}`,
+ type: 'Red',
+ grapes: ['Pinot Noir'],
+ country: 'France',
+ wineryName: 'Produsent',
+ communityRating: 4,
+ communityRatingCount: 10,
+});
+
+/** One page from a catalogue of `total` wines, in the same shape as the API. */
+export function winesPage(total: number, pageSize: number, after?: string) {
+ const start = after ? Number(after) : 0;
+ const end = Math.min(start + pageSize, total);
+ const ids = Array.from({ length: end - start }, (_, i) => start + i + 1);
+ return {
+ data: {
+ wines: {
+ __typename: 'WineConnection',
+ totalCount: total,
+ edges: ids.map((id) => ({
+ __typename: 'WineEdge',
+ cursor: String(id),
+ node: wine(id),
+ })),
+ pageInfo: {
+ __typename: 'PageInfo',
+ hasNextPage: end < total,
+ endCursor: ids.length ? String(end) : null,
+ },
+ },
+ },
+ };
+}
+
+/** A mock that answers every search. `totalFor` decides how many wines a search has. */
+export function searchMock(totalFor: (variables: SentVariables) => number, pageSize = 2) {
+ const resolver = vi.fn((variables: SentVariables) =>
+ winesPage(totalFor(variables), pageSize, variables.after),
+ );
+ const mock: MockLink.MockedResponse = {
+ request: { query: SEARCH_WINES_QUERY, variables: () => true },
+ result: (variables) => resolver(variables as SentVariables),
+ maxUsageCount: Number.POSITIVE_INFINITY,
+ };
+ return { mock, resolver };
+}
From ede1f323153d7d099021b95179d2ab22d5d48ab1 Mon Sep 17 00:00:00 2001
From: Oscar Bakkeng
Date: Fri, 6 Nov 2026 19:10:59 +0100
Subject: [PATCH 3/4] test(frontend): cover routes, landing page and wishlist
(#26)
Co-Authored-By: Claude Opus 5.5
---
frontend/src/app/App.test.tsx | 38 +++++++++++++
.../src/features/landing/LandingPage.test.tsx | 56 +++++++++++++++++++
frontend/src/hooks/useWishlist.test.tsx | 42 ++++++++++++++
3 files changed, 136 insertions(+)
create mode 100644 frontend/src/app/App.test.tsx
create mode 100644 frontend/src/features/landing/LandingPage.test.tsx
create mode 100644 frontend/src/hooks/useWishlist.test.tsx
diff --git a/frontend/src/app/App.test.tsx b/frontend/src/app/App.test.tsx
new file mode 100644
index 0000000..829ca82
--- /dev/null
+++ b/frontend/src/app/App.test.tsx
@@ -0,0 +1,38 @@
+import { Suspense } from 'react';
+import { describe, expect, it } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MockedProvider } from '@apollo/client/testing/react';
+import { MemoryRouter } from 'react-router';
+import { createApolloCache } from '../lib/apollo';
+import { searchMock } from '../test/searchMocks';
+import { AppRoutes } from './App';
+
+function renderRoute(route: string) {
+ render(
+ 1).mock]} cache={createApolloCache()}>
+
+
+
+
+
+ ,
+ );
+}
+
+describe('AppRoutes', () => {
+ it.each([
+ ['/finnes-ikke', 'Fant ikke siden'],
+ ['/vin/1', 'Vin'],
+ ['/mine', 'Mine anmeldelser'],
+ ])('shows the right page for %s', async (route, heading) => {
+ renderRoute(route);
+ expect(await screen.findByRole('heading', { level: 1, name: heading })).toBeInTheDocument();
+ });
+
+ it('loads the search page lazily', async () => {
+ renderRoute('/sok');
+ expect(
+ await screen.findByRole('heading', { level: 1, name: 'Utforsk viner' }),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/features/landing/LandingPage.test.tsx b/frontend/src/features/landing/LandingPage.test.tsx
new file mode 100644
index 0000000..4b7f6ae
--- /dev/null
+++ b/frontend/src/features/landing/LandingPage.test.tsx
@@ -0,0 +1,56 @@
+import { describe, expect, it } from 'vitest';
+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 { LANDING_QUERY } from './api/landingQuery';
+import LandingPage from './LandingPage';
+
+const mock = {
+ request: { query: LANDING_QUERY },
+ result: {
+ data: {
+ topRated: {
+ __typename: 'WineConnection',
+ totalCount: 100,
+ edges: [
+ {
+ __typename: 'WineEdge',
+ node: {
+ __typename: 'Wine',
+ id: '1',
+ name: 'Testvin',
+ type: 'Red',
+ grapes: [],
+ country: 'France',
+ wineryName: 'Produsent',
+ communityRating: 4.5,
+ communityRatingCount: 10,
+ },
+ },
+ ],
+ },
+ filterOptions: {
+ __typename: 'FilterOptions',
+ types: [{ __typename: 'FilterOption', value: 'Red', count: 100 }],
+ countries: [{ __typename: 'FilterOption', value: 'FR' }],
+ },
+ },
+ },
+};
+
+describe('LandingPage', () => {
+ it('shows data from the API and sets the page title', async () => {
+ render(
+
+
+
+
+ ,
+ );
+
+ const region = await screen.findByRole('region', { name: 'Best vurdert' });
+ expect(await within(region).findByRole('link', { name: 'Testvin' })).toBeInTheDocument();
+ expect(document.title).toBe('Kork & Krone – vin anmeldt av studenter');
+ });
+});
diff --git a/frontend/src/hooks/useWishlist.test.tsx b/frontend/src/hooks/useWishlist.test.tsx
new file mode 100644
index 0000000..3496ad9
--- /dev/null
+++ b/frontend/src/hooks/useWishlist.test.tsx
@@ -0,0 +1,42 @@
+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);
+ });
+});
From 88edac5b079c24bd56dc76b7437cbbcf854d9d05 Mon Sep 17 00:00:00 2001
From: Oscar Bakkeng
Date: Fri, 6 Nov 2026 19:10:59 +0100
Subject: [PATCH 4/4] docs(readme): update status after adding the search page
(#26)
Co-Authored-By: Claude Opus 5.5
---
README.md | 32 ++++++++++++++++----------------
1 file changed, 16 insertions(+), 16 deletions(-)
diff --git a/README.md b/README.md
index a1f70e8..8fb22a9 100644
--- a/README.md
+++ b/README.md
@@ -48,8 +48,8 @@ Submission 3 should be the first complete prototype, with search, browsing, sort
| Frontend deployed on the VM | Done | Deep links such as `/project2/sok` work on reload |
| Backend running on the VM | Done | Started with `nohup`, see [VM guide](docs/vm.md) |
| Apollo Client in the frontend | Done | |
-| Search page with results | Next | Placeholder page at `/sok` |
-| Filtering and sorting in the user interface | Planned | Already supported by the API |
+| Search page with results | Done | Search with debounce, number of hits and "Last inn flere" at `/sok` |
+| Filtering and sorting in the user interface | Next | The API and URL filters work, but the panel is missing |
| Wine detail page | Planned | Placeholder page at `/vin/:id` |
| Student reviews (stored in the database) | Planned | |
| Larger dataset on the VM | Planned | |
@@ -98,11 +98,11 @@ This section describes what users can do. "Backend" means the API supports the f
| Feature | Backend | UI | Description |
|---|---|---|---|
-| Search | Done | Planned | Ignores case and accents. Matches name, winery, region and grapes |
+| Search | Done | Done | Ignores case and accents. Matches name, winery, region and grapes as one phrase. Waits 300 ms after the last key press |
| Filtering | Done | Planned | Type, country, grapes, food pairing, minimum rating and alcohol range. Shows the number of wines for each option |
| Sorting | Done | Planned | Top rated, most rated, name and alcohol. Always sorts the whole result, not only the loaded page |
-| Pagination | Done | Planned | Cursor-based. The user loads more results with a button, not with infinite scroll |
-| Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&sort=`. Survives reloads and works with the back button |
+| Pagination | Done | Done | Cursor-based. The user loads more results with a button, not with infinite scroll. Focus moves to the first new wine |
+| Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&sort=`. Survives reloads. Typing replaces the history entry, so the back button leaves the search instead of stepping through every word |
| Wine detail page | Done (`wine(id)`) | Planned | Name, winery, region, grapes, alcohol, food pairing, both ratings, and the latest student reviews |
| Student reviews | Planned | Planned | Die roll from 1 to 6 and an optional comment, stored in PostgreSQL, the new rating is shown at once without a reload (Apollo cache update) |
| Wishlist ("Vil prøve") | Planned | Done, stored in the browser | Moves to the backend when users and reviews are in place |
@@ -134,8 +134,9 @@ Each row explains what we chose, why, and what else we considered. Added as the
| Styling | CSS Modules and design tokens in `styles/tokens.css` | No runtime cost and no extra dependency. Tokens make dark mode and consistent colours easy | Tailwind, styled-components |
| API | GraphQL with Apollo Server on Express | Required by the course. The client asks only for the fields it shows, which saves data | REST |
| Database | PostgreSQL with the `pg_trgm` extension | Fast text search with `ILIKE` also on many rows. Already available on the VM | MongoDB, SQLite |
-| Pagination | Cursor-based | Stable when sorting. No duplicates or gaps when new data is added | Offset-based |
+| Pagination | Cursor-based, pages merged in the Apollo cache | Stable when sorting. No duplicates or gaps when new data is added | Offset-based |
| Search, filtering and sorting | In the database | Scales to large datasets. The frontend never loads the whole catalogue | Filtering in the browser |
+| 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 |
| Testing | Vitest, React Testing Library, Playwright, axe | Vitest shares configuration with Vite. Playwright tests real browsers, also on mobile | Jest, Cypress |
| Deployment | Apache serves static files, the backend runs with `nohup` | Matches the course VM | systemd service (possible improvement) |
@@ -197,7 +198,7 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing,
### Some known gaps
-- The search page, filters and detail page are not built yet, so they are not tested.
+- The filter panel and detail page are not built yet, so they are not tested.
- We have not tested with a screen reader yet.
- eslint-plugin-jsx-a11y is not set up yet.
- The filter panel on mobile will need a dialog with correct focus handling. This is planned.
@@ -219,16 +220,16 @@ We follow the principle from the course: measure, set a budget and show the numb
- The landing page loads all its data in one GraphQL query, with only the fields it shows. An end-to-end test checks that only one request is sent.
- Search, filtering, sorting and pagination run in the database. A page returns at most 50 wines.
- The Apollo cache, so we do not fetch the same data twice.
+- Debounce on the search field (300 ms). An end-to-end test checks that a whole word sends only one search.
**Planned:**
-- Debounce on the search field (about 300 ms), so we do not send a request for every key press.
- Compression (gzip or Brotli) and cache headers in Apache.
### Budget and measurements
| Metric | Budget | Measured | Date | How we measure |
|---|---|---|---|---|
-| JavaScript on the landing page (gzip) | Less than 150 kB | 152,82 kB (over budget after adding Apollo Client) | 6 Nov 2026 | Sum of the gzip sizes from `npm run build` for the files the landing page loads |
+| JavaScript on the landing page (gzip) | Less than 150 kB | 154,01 kB (over budget after adding Apollo Client) | 6 Nov 2026 | Sum of the gzip sizes from `npm run build` for the files the landing page loads |
| Data transferred when loading the landing page | Less than 300 kB | Not measured yet | | Chrome DevTools, Network tab, cache disabled, on the VM |
| Data transferred in a fixed search scenario | Less than 500 kB | Not measured yet | | Same method. Needs the search page |
| Lighthouse (mobile) | Performance at least 90, accessibility 100 | Performance 39, accessibility 100, best practices 100, SEO 100 | 30 Oct 2026 | Lighthouse in Chrome DevTools, incognito, against the VM |
@@ -242,18 +243,16 @@ and because the test was run over VPN. These are the "before" numbers. We will m
| 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, loading, empty and error states, and axe on each component | 70 |
+| 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, loading, empty and error states, and axe on each component | 134 |
| Unit (backend) | Vitest | Parsing of X-Wines CSV files, and building SQL for search, filtering and sorting | 2 test files |
-| End-to-end | Playwright with axe-core, desktop and mobile | One GraphQL request for the landing page (stubbed API), search from the landing page, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 12 (6 tests in 2 browser projects) |
+| End-to-end | Playwright with axe-core, desktop and mobile | Landing page and search page with a stubbed API: one request per page load, debounce, search, load more, reload, back button, no hits, API errors, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 26 (13 tests in 2 browser projects) |
| API | Not set up yet | Resolvers against a test database: search, filtering, sorting and pagination | Planned |
Counted on 6 November 2026.
-**Coverage (frontend, 6 November 2026):** lines 84.26 %, branches 60.69 %, functions 83.33 %, statements 70.19 %.
+**Coverage (frontend, 6 November 2026):** lines 98.32 %, branches 79.6 %, functions 95 %, statements 87.71 %.
Vitest enforces a minimum of 80 % for lines, functions and statements and 75 % for branches (`vitest.config.ts`).
-The coverage run currently fails these limits. The main reasons are hooks without their own tests
-(for example `useWishlist`) and placeholder pages for search and wine details that will be replaced.
We will add the missing tests before raising the limits further, and we do not lower the limits to make the run pass.
We leave out `main.tsx`, test files, test helpers and mock data, because they contain no application logic.
@@ -340,7 +339,7 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a
### Next: complete the beta
1. [x] Add Apollo Client to the frontend, with the endpoint `${import.meta.env.BASE_URL}graphql`.
-2. [ ] Search page: search field with debounce, list of results, number of hits, "Last inn flere", and empty and error states.
+2. [x] Search page: search field with debounce, list of results, number of hits, "Last inn flere", and empty and error states.
3. [ ] Filter panel with counts from `filterOptions`, and sorting. All choices stored in the URL.
4. [x] Connect the landing page to the backend.
5. [ ] Wine detail page.
@@ -358,7 +357,8 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a
### Some known issues
- Some documents in `docs/` still describe the old Vinmonopolet plan and the old test endpoint `/api/hello`. They will be updated.
-- Frontend test coverage is below our enforced limits (statements 70.19 %, branches 60.69 %). Tests for `useWishlist` and the remaining components are planned.
+- Search matches the text as one phrase, so "noir pinot" finds nothing. Country is not part of the search text, because the country filter covers it.
+- The cursors in the API hold an offset, which is slower deep into large results. To be solved together with the larger dataset.