From eae99bb456d801c57c2a1681632230e94c550f00 Mon Sep 17 00:00:00 2001
From: Oscar Bakkeng
Date: Sat, 7 Nov 2026 18:58:57 +0100
Subject: [PATCH 1/3] feat(backend): add filter counts that follow the search
(#35)
filterOptions now takes the search and the filters, and returns grapes
and food pairings as well. Each group leaves out its own filter, so the
other values show what they would add. Only requested groups are counted.
Co-Authored-By: Claude Opus 5.5
---
backend/src/resolvers.ts | 35 ++++++++++++------
backend/src/schema.ts | 8 +++--
backend/src/wine-query.test.ts | 65 ++++++++++++++++++++++++++++++++-
backend/src/wine-query.ts | 66 ++++++++++++++++++++++++++++------
docs/api.md | 5 ++-
5 files changed, 155 insertions(+), 24 deletions(-)
diff --git a/backend/src/resolvers.ts b/backend/src/resolvers.ts
index 331d232..01988e2 100644
--- a/backend/src/resolvers.ts
+++ b/backend/src/resolvers.ts
@@ -1,6 +1,12 @@
// Resolvers: the functions that fetch data for each field in the schema.
import { pool } from './db';
-import { buildWinesQuery, encodeCursor, type WinesArgs } from './wine-query';
+import {
+ buildFilterOptionsQueries,
+ buildWinesQuery,
+ encodeCursor,
+ type FilterArgs,
+ type WinesArgs,
+} from './wine-query';
// A row from the wine table, as returned by pg.
interface WineRow {
@@ -46,6 +52,14 @@ function toWine(row: WineRow) {
};
}
+async function filterOptions(
+ args: FilterArgs,
+ group: keyof ReturnType,
+) {
+ const { sql, params } = buildFilterOptionsQueries(args)[group];
+ return (await pool.query(sql, params)).rows;
+}
+
export const resolvers = {
Query: {
async wines(_parent: unknown, args: WinesArgs) {
@@ -78,15 +92,16 @@ export const resolvers = {
return result.rows[0] ? toWine(result.rows[0]) : null;
},
- async filterOptions() {
- const [types, countries] = await Promise.all([
- pool.query(`SELECT type AS value, type AS label, count(*)::int AS count
- FROM wine GROUP BY type ORDER BY count DESC, type`),
- pool.query(`SELECT country_code AS value, max(country) AS label, count(*)::int AS count
- FROM wine WHERE country_code IS NOT NULL
- GROUP BY country_code ORDER BY count DESC, label`),
- ]);
- return { types: types.rows, countries: countries.rows };
+ // The counts are in the fields below, so a query only pays for the groups it asks for.
+ filterOptions(_parent: unknown, args: FilterArgs) {
+ return args;
},
},
+
+ FilterOptions: {
+ types: (args: FilterArgs) => filterOptions(args, 'types'),
+ countries: (args: FilterArgs) => filterOptions(args, 'countries'),
+ grapes: (args: FilterArgs) => filterOptions(args, 'grapes'),
+ harmonize: (args: FilterArgs) => filterOptions(args, 'harmonize'),
+ },
};
\ No newline at end of file
diff --git a/backend/src/schema.ts b/backend/src/schema.ts
index d953014..96fd132 100644
--- a/backend/src/schema.ts
+++ b/backend/src/schema.ts
@@ -68,6 +68,10 @@ export const typeDefs = `#graphql
type FilterOptions {
types: [FilterOption!]!
countries: [FilterOption!]!
+ "The most common grapes."
+ grapes: [FilterOption!]!
+ "The most common food pairings."
+ harmonize: [FilterOption!]!
}
type Query {
@@ -82,7 +86,7 @@ export const typeDefs = `#graphql
wine(id: ID!): Wine
- "Values for the filter panel, with the number of wines for each value."
- filterOptions: FilterOptions!
+ "Values for the filter panel. The counts follow the search and the filters in the other groups."
+ filterOptions(search: String, filter: WineFilter): FilterOptions!
}
`;
\ No newline at end of file
diff --git a/backend/src/wine-query.test.ts b/backend/src/wine-query.test.ts
index 09abfa2..7befe7d 100644
--- a/backend/src/wine-query.test.ts
+++ b/backend/src/wine-query.test.ts
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vitest';
-import { buildWinesQuery, decodeCursor, encodeCursor, MAX_PAGE_SIZE } from './wine-query';
+import {
+ buildFilterOptionsQueries,
+ buildWinesQuery,
+ decodeCursor,
+ encodeCursor,
+ MAX_FACET_VALUES,
+ MAX_PAGE_SIZE,
+} from './wine-query';
describe('buildWinesQuery', () => {
it('returns all wines sorted by top rating when there are no arguments', () => {
@@ -50,6 +57,62 @@ describe('buildWinesQuery', () => {
});
});
+describe('buildFilterOptionsQueries', () => {
+ const args = {
+ search: 'pinot',
+ filter: {
+ types: ['Red'],
+ countryCodes: ['FR'],
+ grapes: ['Merlot'],
+ harmonize: ['Beef'],
+ minRating: 4,
+ },
+ };
+
+ it('counts all wines when there is no search or filter', () => {
+ const { types } = buildFilterOptionsQueries({});
+ expect(types.sql).not.toContain('WHERE');
+ expect(types.params).toEqual([]);
+ });
+
+ it('leaves out its own filter, so the other values in the group still have a count', () => {
+ const { types, countries, grapes, harmonize } = buildFilterOptionsQueries(args);
+ expect(types.params).toEqual(['%pinot%', ['FR'], ['Merlot'], ['Beef'], 4]);
+ expect(countries.params).toEqual(['%pinot%', ['Red'], ['Merlot'], ['Beef'], 4]);
+ expect(grapes.params).toEqual(['%pinot%', ['Red'], ['FR'], ['Beef'], 4]);
+ expect(harmonize.params).toEqual(['%pinot%', ['Red'], ['FR'], ['Merlot'], 4]);
+ });
+
+ it('keeps the search and the other filters', () => {
+ const { types } = buildFilterOptionsQueries(args);
+ expect(types.sql).toContain('search_text ILIKE $1');
+ expect(types.sql).toContain('country_code = ANY($2)');
+ expect(types.sql).not.toContain('type = ANY');
+ });
+
+ it('leaves out wines without a country', () => {
+ expect(buildFilterOptionsQueries({}).countries.sql).toContain('WHERE country_code IS NOT NULL');
+ expect(buildFilterOptionsQueries(args).countries.sql).toContain('AND country_code IS NOT NULL');
+ });
+
+ it('splits the lists of grapes and food into one row per value', () => {
+ const { grapes, harmonize } = buildFilterOptionsQueries({});
+ expect(grapes.sql).toContain('unnest(grapes)');
+ expect(harmonize.sql).toContain('unnest(harmonize)');
+ });
+
+ it('limits the number of grapes and food values, since there can be thousands', () => {
+ const { grapes, harmonize } = buildFilterOptionsQueries({});
+ expect(grapes.sql).toContain(`LIMIT ${MAX_FACET_VALUES}`);
+ expect(harmonize.sql).toContain(`LIMIT ${MAX_FACET_VALUES}`);
+ });
+
+ it('never puts the search text in the SQL itself', () => {
+ const { grapes } = buildFilterOptionsQueries({ search: "'; DROP TABLE wine; --" });
+ expect(grapes.sql).not.toContain('DROP TABLE');
+ });
+});
+
describe('cursor', () => {
it('round-trips an offset', () => {
expect(decodeCursor(encodeCursor(48))).toBe(48);
diff --git a/backend/src/wine-query.ts b/backend/src/wine-query.ts
index 9e45ac3..08df7fb 100644
--- a/backend/src/wine-query.ts
+++ b/backend/src/wine-query.ts
@@ -14,9 +14,12 @@ export interface WineFilter {
maxAbv?: number | null;
}
-export interface WinesArgs {
+export interface FilterArgs {
search?: string | null;
filter?: WineFilter | null;
+}
+
+export interface WinesArgs extends FilterArgs {
sort?: WineSort | null;
first?: number | null;
after?: string | null;
@@ -24,6 +27,9 @@ export interface WinesArgs {
export const MAX_PAGE_SIZE = 50;
+// Enough for the filter panel. The Full dataset has far more grapes than anyone scrolls through.
+export const MAX_FACET_VALUES = 40;
+
// Only these ORDER BY clauses can ever reach the database. "id" last makes the order stable.
const ORDER_BY: Record = {
TOP_RATED: 'community_avg DESC NULLS LAST, community_count DESC, id',
@@ -53,19 +59,21 @@ function escapeLike(text: string): string {
return text.replace(/[\\%_]/g, (char) => `\\${char}`);
}
-export function buildWinesQuery(args: WinesArgs) {
- const where: string[] = [];
- const params: unknown[] = [];
- // Adds a value to params and returns its placeholder ($1, $2, ...). Never put user input in the SQL string.
- const param = (value: unknown) => {
+/** Adds a value to params and returns its placeholder ($1, $2, ...). Never put user input in the SQL string. */
+function addParam(params: unknown[], value: unknown): string {
params.push(value);
return `$${params.length}`;
- };
+}
+
+/** The search and the filters as WHERE conditions. `omit` leaves out one filter, for the counts. */
+function buildWhere(args: FilterArgs, params: unknown[], omit?: keyof WineFilter): string[] {
+ const where: string[] = [];
+ const param = (value: unknown) => addParam(params, value);
const search = toSearchText(args.search ?? '');
if (search) where.push(`search_text ILIKE ${param(`%${escapeLike(search)}%`)}`);
- const filter = args.filter ?? {};
+ const filter: WineFilter = { ...args.filter, ...(omit && { [omit]: null }) };
if (filter.types?.length) where.push(`type = ANY(${param(filter.types)})`);
if (filter.countryCodes?.length) where.push(`country_code = ANY(${param(filter.countryCodes)})`);
// && means "the lists have at least one value in common".
@@ -74,8 +82,46 @@ export function buildWinesQuery(args: WinesArgs) {
if (filter.minRating != null) where.push(`community_avg >= ${param(filter.minRating)}`);
if (filter.minAbv != null) where.push(`abv >= ${param(filter.minAbv)}`);
if (filter.maxAbv != null) where.push(`abv <= ${param(filter.maxAbv)}`);
+ return where;
+}
+
+const toWhereSql = (where: string[]) => (where.length ? `WHERE ${where.join(' AND ')}` : '');
+
+/**
+ * One count query per filter group, for the numbers in the filter panel. Each query leaves
+ * out the group's own filter: with "Red" selected, "White" still shows what it would add.
+ */
+export function buildFilterOptionsQueries(args: FilterArgs) {
+ const query = (omit: keyof WineFilter, build: (where: string[]) => string) => {
+ const params: unknown[] = [];
+ return { sql: build(buildWhere(args, params, omit)), params };
+ };
+ // Grapes and food are lists on each wine, so each value in a list becomes its own row.
+ const listValues = (column: 'grapes' | 'harmonize') => (where: string[]) =>
+ `SELECT value, value AS label, count(*)::int AS count
+ FROM wine CROSS JOIN LATERAL unnest(${column}) AS value ${toWhereSql(where)}
+ GROUP BY value ORDER BY count DESC, value LIMIT ${MAX_FACET_VALUES}`;
- const whereSql = where.length ? `WHERE ${where.join(' AND ')}` : '';
+ return {
+ types: query(
+ 'types',
+ (where) => `SELECT type AS value, type AS label, count(*)::int AS count
+ FROM wine ${toWhereSql(where)} GROUP BY type ORDER BY count DESC, type`,
+ ),
+ countries: query(
+ 'countryCodes',
+ (where) => `SELECT country_code AS value, max(country) AS label, count(*)::int AS count
+ FROM wine ${toWhereSql([...where, 'country_code IS NOT NULL'])}
+ GROUP BY country_code ORDER BY count DESC, label`,
+ ),
+ grapes: query('grapes', listValues('grapes')),
+ harmonize: query('harmonize', listValues('harmonize')),
+ };
+}
+
+export function buildWinesQuery(args: WinesArgs) {
+ const params: unknown[] = [];
+ const whereSql = toWhereSql(buildWhere(args, params));
const orderBy = ORDER_BY[args.sort ?? 'TOP_RATED'];
if (!orderBy) throw new Error('Invalid sort.');
@@ -85,7 +131,7 @@ export function buildWinesQuery(args: WinesArgs) {
// Fetch one extra row to know if there is a next page.
const listSql = `SELECT * FROM wine ${whereSql} ORDER BY ${orderBy}
- LIMIT ${param(first + 1)} OFFSET ${param(offset)}`;
+ LIMIT ${addParam(params, first + 1)} OFFSET ${addParam(params, offset)}`;
const countSql = `SELECT count(*)::int AS total FROM wine ${whereSql}`;
return { listSql, listParams: params, countSql, countParams, first, offset };
diff --git a/docs/api.md b/docs/api.md
index 5ea3dfe..80a1be4 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -27,7 +27,10 @@ https://doi.org/10.3390/bdcc7010020
Returns `totalCount`, `edges { cursor node }` and `pageInfo { hasNextPage endCursor }`.
Pass `pageInfo.endCursor` as `after` to load the next page. `first` is at most 50.
- `wine(id)`: one wine, or `null` if it does not exist.
-- `filterOptions`: values for the filter panel with the number of wines per value.
+- `filterOptions(search, filter)`: values for the filter panel with the number of wines per value.
+ The counts follow the search and the filters in the other groups, but not the group's own filter:
+ with `Red` selected, `White` still shows what it would add. `grapes` and `harmonize` return the 40
+ most common values. Only the requested groups are counted.
Search is case and accent insensitive and matches name, winery, region and grapes.
Several values in one filter list mean OR. Search and different filters are combined with AND.
From cee6a09505870d78d4fc4d3e1efa3da491bbda1d Mon Sep 17 00:00:00 2001
From: Oscar Bakkeng
Date: Sat, 7 Nov 2026 18:58:57 +0100
Subject: [PATCH 2/3] feat(search): add filter panel and sorting (#35)
Several values can be selected, and all choices live in the URL. On small
screens the filters open in a native dialog. Active filters can be removed
one by one, and the back button undoes the last choice. Wine cards now show
countries in Norwegian.
Co-Authored-By: Claude Opus 5.5
---
frontend/e2e/filters.spec.ts | 178 +++++++++++
frontend/e2e/landing.spec.ts | 1 +
frontend/e2e/search.spec.ts | 1 +
frontend/src/app/App.test.tsx | 10 +-
frontend/src/components/ui/Chip.tsx | 6 +-
.../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 +
.../landing/components/CategoryList.tsx | 2 +-
frontend/src/features/landing/suggestions.ts | 8 +-
.../features/search/SearchFilters.test.tsx | 296 ++++++++++++++++++
frontend/src/features/search/SearchPage.tsx | 23 +-
.../src/features/search/SearchView.module.css | 57 ++++
frontend/src/features/search/SearchView.tsx | 151 ++++++---
.../features/search/api/filterOptionsQuery.ts | 29 ++
.../src/features/search/api/searchQuery.ts | 1 +
.../search/api/searchVariables.test.ts | 39 ++-
.../features/search/api/searchVariables.ts | 74 +++--
.../search/api/toFilterGroups.test.ts | 68 ++++
.../src/features/search/api/toFilterGroups.ts | 110 +++++++
.../features/search/api/useFilterOptions.ts | 20 ++
.../components/ActiveFilters.module.css | 16 +
.../search/components/ActiveFilters.tsx | 51 +++
.../search/components/FilterDialog.module.css | 68 ++++
.../search/components/FilterDialog.tsx | 60 ++++
.../search/components/FilterPanel.module.css | 76 +++++
.../search/components/FilterPanel.tsx | 132 ++++++++
frontend/src/features/search/filterLabels.ts | 10 +
frontend/src/features/wine/WineView.tsx | 4 +-
.../src/features/wine/api/toWineDetails.ts | 3 -
frontend/src/hooks/useMediaQuery.ts | 15 +
frontend/src/lib/apollo.ts | 2 +
frontend/src/lib/mapWine.test.ts | 10 +-
frontend/src/lib/mapWine.ts | 6 +-
frontend/src/lib/searchParams.test.ts | 99 +++++-
frontend/src/lib/searchParams.ts | 132 ++++++--
frontend/src/test/searchMocks.ts | 33 ++
38 files changed, 1655 insertions(+), 140 deletions(-)
create mode 100644 frontend/e2e/filters.spec.ts
create mode 100644 frontend/src/features/search/SearchFilters.test.tsx
create mode 100644 frontend/src/features/search/api/filterOptionsQuery.ts
create mode 100644 frontend/src/features/search/api/toFilterGroups.test.ts
create mode 100644 frontend/src/features/search/api/toFilterGroups.ts
create mode 100644 frontend/src/features/search/api/useFilterOptions.ts
create mode 100644 frontend/src/features/search/components/ActiveFilters.module.css
create mode 100644 frontend/src/features/search/components/ActiveFilters.tsx
create mode 100644 frontend/src/features/search/components/FilterDialog.module.css
create mode 100644 frontend/src/features/search/components/FilterDialog.tsx
create mode 100644 frontend/src/features/search/components/FilterPanel.module.css
create mode 100644 frontend/src/features/search/components/FilterPanel.tsx
create mode 100644 frontend/src/features/search/filterLabels.ts
create mode 100644 frontend/src/hooks/useMediaQuery.ts
diff --git a/frontend/e2e/filters.spec.ts b/frontend/e2e/filters.spec.ts
new file mode 100644
index 0000000..72ff66c
--- /dev/null
+++ b/frontend/e2e/filters.spec.ts
@@ -0,0 +1,178 @@
+import AxeBuilder from '@axe-core/playwright';
+import { expect, test, type Page } from '@playwright/test';
+
+/*
+ * E2E for filters and sorting. Runs against `vite preview` with a stubbed GraphQL API.
+ * The desktop project uses the sidebar, and the mobile project uses the dialog.
+ */
+interface Variables {
+ sort?: string;
+ filter?: { types?: string[] };
+}
+
+const wine = (id: number, type: string) => ({
+ __typename: 'Wine',
+ id: String(id),
+ name: `${type} ${id}`,
+ type,
+ grapes: ['Merlot'],
+ country: 'Italy',
+ countryCode: 'IT',
+ wineryName: 'Testprodusent',
+ communityRating: 4,
+ communityRatingCount: 10,
+});
+
+function winesResponse({ filter, sort }: Variables) {
+ const types = filter?.types ?? ['Red', 'White'];
+ const wines = types.map((type, index) => wine(index + 1, type));
+ if (sort === 'NAME_ASC') wines.reverse();
+ return {
+ data: {
+ wines: {
+ __typename: 'WineConnection',
+ totalCount: wines.length,
+ edges: wines.map((node) => ({ __typename: 'WineEdge', cursor: node.id, node })),
+ pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null },
+ },
+ },
+ };
+}
+
+const option = (value: string, count: number) => ({
+ __typename: 'FilterOption',
+ value,
+ label: value,
+ count,
+});
+
+const filterResponse = {
+ data: {
+ filterOptions: {
+ __typename: 'FilterOptions',
+ types: [option('Red', 53), option('White', 19)],
+ countries: [option('IT', 25)],
+ grapes: [option('Merlot', 9)],
+ harmonize: [option('Beef', 53)],
+ },
+ },
+};
+
+async function stubApi(page: Page) {
+ await page.route('**/project2/graphql', (route) => {
+ const { operationName, variables } = route.request().postDataJSON() as {
+ operationName: string;
+ variables: Variables;
+ };
+ return route.fulfill({
+ json: operationName === 'FilterOptions' ? filterResponse : winesResponse(variables),
+ });
+ });
+}
+
+/** Opens the dialog on mobile. On desktop the filters are always visible. */
+async function openFilters(page: Page, isMobile: boolean) {
+ if (isMobile) await page.getByRole('button', { name: /^Filtrer/ }).click();
+}
+
+async function closeFilters(page: Page, isMobile: boolean) {
+ if (isMobile) await page.getByRole('button', { name: /^Vis \d+/ }).click();
+}
+
+const results = (page: Page) => page.getByRole('list', { name: 'Søkeresultater' });
+
+test.describe('Filter og sortering', () => {
+ test.beforeEach(async ({ page }) => {
+ await stubApi(page);
+ await page.goto('./sok');
+ await expect(results(page).getByRole('article')).toHaveCount(2);
+ });
+
+ test('filtrer, sorter, last på nytt, angre og nullstill', async ({ page, isMobile }) => {
+ await openFilters(page, isMobile);
+ await page.getByRole('checkbox', { name: /Rødvin/ }).check();
+ await closeFilters(page, isMobile);
+
+ await expect(page).toHaveURL(/\/sok\?type=rodvin$/);
+ await expect(results(page).getByRole('article')).toHaveCount(1);
+ await expect(page.getByRole('link', { name: 'Fjern filteret Rødvin' })).toBeVisible();
+
+ await page.getByRole('combobox', { name: 'Sorter etter' }).selectOption('name');
+ await expect(page).toHaveURL(/\/sok\?type=rodvin&sort=name$/);
+
+ await page.reload();
+ await expect(page.getByRole('combobox', { name: 'Sorter etter' })).toHaveValue('name');
+ await expect(page.getByRole('link', { name: 'Fjern filteret Rødvin' })).toBeVisible();
+
+ await page.goBack();
+ await expect(page).toHaveURL(/\/sok\?type=rodvin$/);
+
+ await page.getByRole('link', { name: 'Nullstill filtre' }).click();
+ await expect(page).toHaveURL(/\/sok$/);
+ await expect(results(page).getByRole('article')).toHaveCount(2);
+ });
+
+ test('har ingen axe-brudd (WCAG 2.1 AA)', async ({ page, isMobile }) => {
+ await openFilters(page, isMobile);
+ await expect(page.getByRole('checkbox', { name: /Rødvin/ })).toBeVisible();
+ const axe = await new AxeBuilder({ page })
+ .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
+ .analyze();
+ expect(axe.violations).toEqual([]);
+ });
+
+ test('filtrene kan brukes med bare tastatur', async ({ page, isMobile }) => {
+ await openFilters(page, isMobile);
+ const box = page.getByRole('checkbox', { name: /Rødvin/ });
+ await box.focus();
+ await page.keyboard.press('Space');
+ await expect(page).toHaveURL(/type=rodvin/);
+ await expect(box).toBeFocused();
+ await expect(box).toBeChecked();
+ });
+
+ test('har ingen horisontal scroll ved 320 px med aktive filtre', async ({ page }) => {
+ await page.setViewportSize({ width: 320, height: 640 });
+ await page.goto('./sok?type=rodvin&land=IT&vurdering=4&alkohol=hoy');
+ await expect(results(page).getByRole('article')).toHaveCount(1);
+ const overflow = await page.evaluate(
+ () => document.documentElement.scrollWidth > window.innerWidth,
+ );
+ expect(overflow).toBe(false);
+ });
+});
+
+test.describe('Filterdialogen på mobil', () => {
+ test.beforeEach(async ({ page, isMobile }) => {
+ test.skip(!isMobile, 'Dialogen finnes bare på små skjermer.');
+ await stubApi(page);
+ await page.goto('./sok');
+ await expect(results(page).getByRole('article')).toHaveCount(2);
+ });
+
+ test('Escape lukker dialogen og gir fokus tilbake til knappen', async ({ page }) => {
+ const opener = page.getByRole('button', { name: 'Filtrer' });
+ await opener.click();
+ await expect(page.getByRole('dialog', { name: 'Filtrer' })).toBeVisible();
+
+ await page.keyboard.press('Escape');
+
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+ await expect(opener).toBeFocused();
+ });
+
+ test('tastaturfokus blir værende i dialogen', async ({ page }) => {
+ await page.getByRole('button', { name: 'Filtrer' }).click();
+ await expect(page.getByRole('checkbox', { name: /Rødvin/ })).toBeVisible();
+
+ for (let press = 0; press < 25; press += 1) {
+ await page.keyboard.press('Tab');
+ // The focus can also leave the page for the browser, which gives `body`.
+ const outside = await page.evaluate(
+ () =>
+ document.activeElement !== document.body && !document.activeElement?.closest('dialog'),
+ );
+ expect(outside).toBe(false);
+ }
+ });
+});
diff --git a/frontend/e2e/landing.spec.ts b/frontend/e2e/landing.spec.ts
index 876c48a..56e630b 100644
--- a/frontend/e2e/landing.spec.ts
+++ b/frontend/e2e/landing.spec.ts
@@ -12,6 +12,7 @@ const wines = Array.from({ length: 6 }, (_, i) => ({
type: 'Red',
grapes: ['Pinot Noir'],
country: 'France',
+ countryCode: 'FR',
wineryName: 'Testprodusent',
communityRating: 4.5,
communityRatingCount: 10,
diff --git a/frontend/e2e/search.spec.ts b/frontend/e2e/search.spec.ts
index 8a310c2..cea717d 100644
--- a/frontend/e2e/search.spec.ts
+++ b/frontend/e2e/search.spec.ts
@@ -18,6 +18,7 @@ const wine = (id: number) => ({
type: 'Red',
grapes: ['Pinot Noir'],
country: 'France',
+ countryCode: 'FR',
wineryName: 'Testprodusent',
communityRating: 4.5,
communityRatingCount: 10,
diff --git a/frontend/src/app/App.test.tsx b/frontend/src/app/App.test.tsx
index 64b0663..19da5e0 100644
--- a/frontend/src/app/App.test.tsx
+++ b/frontend/src/app/App.test.tsx
@@ -19,6 +19,10 @@ function renderRoute(route: string) {
);
}
+/** The pages are lazy, and the import takes longer when the whole test suite runs at once. */
+const findHeading = (name: string) =>
+ screen.findByRole('heading', { level: 1, name }, { timeout: 5000 });
+
describe('AppRoutes', () => {
it.each([
['/finnes-ikke', 'Fant ikke siden'],
@@ -26,13 +30,11 @@ describe('AppRoutes', () => {
['/mine', 'Mine anmeldelser'],
])('shows the right page for %s', async (route, heading) => {
renderRoute(route);
- expect(await screen.findByRole('heading', { level: 1, name: heading })).toBeInTheDocument();
+ expect(await findHeading(heading)).toBeInTheDocument();
});
it('loads the search page lazily', async () => {
renderRoute('/sok');
- expect(
- await screen.findByRole('heading', { level: 1, name: 'Utforsk viner' }),
- ).toBeInTheDocument();
+ expect(await findHeading('Utforsk viner')).toBeInTheDocument();
});
});
diff --git a/frontend/src/components/ui/Chip.tsx b/frontend/src/components/ui/Chip.tsx
index 9e7421b..ed0eb8c 100644
--- a/frontend/src/components/ui/Chip.tsx
+++ b/frontend/src/components/ui/Chip.tsx
@@ -7,15 +7,17 @@ interface ChipLinkProps {
children: ReactNode;
/** `onBrand` brukes på vinrød bakgrunn. */
tone?: 'default' | 'onBrand';
+ /** Replaces the visible text for screen readers when it says too little on its own. */
+ label?: string;
}
/**
* Chip som navigerer (forslag, kategorier, aktive filtre som lenker).
* Det er en lenke – ikke en knapp – fordi den endrer side/URL.
*/
-export function ChipLink({ to, children, tone = 'default' }: ChipLinkProps) {
+export function ChipLink({ to, children, tone = 'default', label }: ChipLinkProps) {
return (
-
+
{children}
);
diff --git a/frontend/src/features/landing/LandingPage.test.tsx b/frontend/src/features/landing/LandingPage.test.tsx
index 4b7f6ae..7210ffb 100644
--- a/frontend/src/features/landing/LandingPage.test.tsx
+++ b/frontend/src/features/landing/LandingPage.test.tsx
@@ -23,6 +23,7 @@ const mock = {
type: 'Red',
grapes: [],
country: 'France',
+ countryCode: 'FR',
wineryName: 'Produsent',
communityRating: 4.5,
communityRatingCount: 10,
diff --git a/frontend/src/features/landing/api/landingQuery.ts b/frontend/src/features/landing/api/landingQuery.ts
index 7ece9ea..4cd1cb5 100644
--- a/frontend/src/features/landing/api/landingQuery.ts
+++ b/frontend/src/features/landing/api/landingQuery.ts
@@ -15,6 +15,7 @@ export const LANDING_QUERY = gql`
type
grapes
country
+ countryCode
wineryName
communityRating
communityRatingCount
diff --git a/frontend/src/features/landing/api/toLandingData.test.ts b/frontend/src/features/landing/api/toLandingData.test.ts
index b7d6fce..fc2dece 100644
--- a/frontend/src/features/landing/api/toLandingData.test.ts
+++ b/frontend/src/features/landing/api/toLandingData.test.ts
@@ -8,6 +8,7 @@ const wine = (id: string, type = 'Red'): ApiWine => ({
type,
grapes: [],
country: 'France',
+ countryCode: 'FR',
wineryName: 'Winery',
communityRating: 4,
communityRatingCount: 10,
diff --git a/frontend/src/features/landing/api/useLandingData.test.tsx b/frontend/src/features/landing/api/useLandingData.test.tsx
index 245f08d..03fcda7 100644
--- a/frontend/src/features/landing/api/useLandingData.test.tsx
+++ b/frontend/src/features/landing/api/useLandingData.test.tsx
@@ -21,6 +21,7 @@ const result = {
type: 'White',
grapes: ['Riesling'],
country: 'Germany',
+ countryCode: 'DE',
wineryName: 'Winery',
communityRating: 4.2,
communityRatingCount: 12,
diff --git a/frontend/src/features/landing/components/CategoryList.tsx b/frontend/src/features/landing/components/CategoryList.tsx
index 74d9874..7d6934e 100644
--- a/frontend/src/features/landing/components/CategoryList.tsx
+++ b/frontend/src/features/landing/components/CategoryList.tsx
@@ -22,7 +22,7 @@ export function CategoryList({ categories }: { categories: CategoryCount[] }) {
return (
diff --git a/frontend/src/features/landing/suggestions.ts b/frontend/src/features/landing/suggestions.ts
index 16c2db7..b6d50d0 100644
--- a/frontend/src/features/landing/suggestions.ts
+++ b/frontend/src/features/landing/suggestions.ts
@@ -2,9 +2,9 @@ import type { SearchState } from '../../lib/searchParams';
/** Forslag som snarveier inn i søket. Lagt her så de er enkle å endre/teste. */
export const SUGGESTIONS: { label: string; search: SearchState }[] = [
- { label: 'Til pizza', search: { food: 'Pizza' } },
- { label: 'Riesling', search: { grape: 'Riesling' } },
- { label: 'Italiensk rødvin', search: { type: 'RED', country: 'IT' } },
- { label: 'Bobler til feiring', search: { type: 'SPARKLING' } },
+ { label: 'Til pizza', search: { foods: ['Pizza'] } },
+ { label: 'Riesling', search: { grapes: ['Riesling'] } },
+ { label: 'Italiensk rødvin', search: { types: ['RED'], countries: ['IT'] } },
+ { label: 'Bobler til feiring', search: { types: ['SPARKLING'] } },
{ label: 'Best likt av studenter', search: { sort: 'rating' } },
];
diff --git a/frontend/src/features/search/SearchFilters.test.tsx b/frontend/src/features/search/SearchFilters.test.tsx
new file mode 100644
index 0000000..865ac74
--- /dev/null
+++ b/frontend/src/features/search/SearchFilters.test.tsx
@@ -0,0 +1,296 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { MockLink } from '@apollo/client/testing';
+import { MockedProvider } from '@apollo/client/testing/react';
+import { MemoryRouter, Route, Routes } from 'react-router';
+import { axe } from 'vitest-axe';
+import { createApolloCache } from '../../lib/apollo';
+import { LocationProbe } from '../../test/LocationProbe';
+import { filterOptionsMock, searchMock } from '../../test/searchMocks';
+import SearchPage from './SearchPage';
+
+function setScreen(wide: boolean) {
+ vi.stubGlobal('matchMedia', () => ({
+ matches: wide,
+ addEventListener: () => undefined,
+ removeEventListener: () => undefined,
+ }));
+}
+
+function renderPage(mocks: MockLink.MockedResponse[], route = '/sok') {
+ const user = userEvent.setup();
+ const result = render(
+
+
+
+ } />
+ Annen side
} />
+
+
+
+ ,
+ );
+ return { user, ...result };
+}
+
+const location = () => screen.getByTestId('location');
+const panel = () => screen.findByRole('complementary', { name: 'Filtre' });
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('Filter på stor skjerm', () => {
+ beforeEach(() => setScreen(true));
+
+ it('viser filtrene med antall viner', async () => {
+ renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
+ const filters = await panel();
+ expect(await within(filters).findByRole('checkbox', { name: /Rødvin/ })).toHaveAccessibleName(
+ 'Rødvin, 53 viner',
+ );
+ expect(within(filters).getByRole('group', { name: 'Land' })).toBeInTheDocument();
+ expect(within(filters).getByRole('checkbox', { name: /Storfe/ })).toBeInTheDocument();
+ });
+
+ it('legger valget i URL-en og beholder søket', async () => {
+ const { user } = renderPage(
+ [searchMock(() => 3).mock, filterOptionsMock().mock],
+ '/sok?q=pinot',
+ );
+ await user.click(await screen.findByRole('checkbox', { name: /Rødvin/ }));
+ expect(location()).toHaveTextContent('/sok?q=pinot&type=rodvin');
+ });
+
+ it('kan velge flere verdier og sender alle til API-et', async () => {
+ const { mock, resolver } = searchMock(() => 3);
+ const { user } = renderPage([mock, filterOptionsMock().mock]);
+ await user.click(await screen.findByRole('checkbox', { name: /Rødvin/ }));
+ await user.click(await screen.findByRole('checkbox', { name: /Hvitvin/ }));
+
+ await waitFor(() =>
+ expect(resolver).toHaveBeenCalledWith(
+ expect.objectContaining({ filter: { types: ['Red', 'White'] } }),
+ ),
+ );
+ expect(location()).toHaveTextContent('type=rodvin&type=hvitvin');
+ });
+
+ it('beholder fokus i avkrysningsboksen etter et valg', async () => {
+ const { user } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
+ const box = await screen.findByRole('checkbox', { name: /Rødvin/ });
+ await user.click(box);
+ await waitFor(() => expect(location()).toHaveTextContent('type=rodvin'));
+ expect(screen.getByRole('checkbox', { name: /Rødvin/ })).toHaveFocus();
+ });
+
+ it('fjerner valget ved nytt klikk', async () => {
+ const { user } = renderPage(
+ [searchMock(() => 3).mock, filterOptionsMock().mock],
+ '/sok?type=rodvin',
+ );
+ const box = await screen.findByRole('checkbox', { name: /Rødvin/ });
+ expect(box).toBeChecked();
+ await user.click(box);
+ expect(location()).toHaveTextContent(/^\/sok$/);
+ });
+
+ it('viser filtre fra URL-en som valgt etter omlasting', async () => {
+ renderPage([searchMock(() => 3).mock, filterOptionsMock().mock], '/sok?land=IT&mat=Beef');
+ expect(await screen.findByRole('checkbox', { name: /Italia/ })).toBeChecked();
+ expect(screen.getByRole('checkbox', { name: /Storfe/ })).toBeChecked();
+ });
+
+ it('beholder et valg uten treff, så det kan fjernes', async () => {
+ renderPage([searchMock(() => 0).mock, filterOptionsMock().mock], '/sok?drue=Ukjent');
+ expect(await screen.findByRole('checkbox', { name: 'Ukjent, 0 viner' })).toBeChecked();
+ });
+
+ it('skjuler lange lister bak en knapp', async () => {
+ const { user } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
+ const grapes = await screen.findByRole('group', { name: 'Drue' });
+ await within(grapes).findAllByRole('checkbox');
+ expect(within(grapes).getAllByRole('checkbox')).toHaveLength(6);
+
+ await user.click(within(grapes).getByRole('button', { name: 'Vis alle i Drue (8)' }));
+
+ expect(within(grapes).getAllByRole('checkbox')).toHaveLength(8);
+ await user.click(within(grapes).getByRole('button', { name: 'Vis færre i Drue' }));
+ expect(within(grapes).getAllByRole('checkbox')).toHaveLength(6);
+ });
+
+ it('viser alltid et valgt filter, også når listen er kort', async () => {
+ renderPage([searchMock(() => 3).mock, filterOptionsMock().mock], '/sok?drue=Drue8');
+ const grapes = await screen.findByRole('group', { name: 'Drue' });
+ expect(await within(grapes).findByRole('checkbox', { name: /Drue8/ })).toBeChecked();
+ });
+
+ it('filtrerer på minimumsvurdering', async () => {
+ const { mock, resolver } = searchMock(() => 3);
+ const { user } = renderPage([mock, filterOptionsMock().mock]);
+ await user.selectOptions(await screen.findByRole('combobox', { name: 'Vurdering' }), '4');
+ expect(location()).toHaveTextContent('/sok?vurdering=4');
+ await waitFor(() =>
+ expect(resolver).toHaveBeenCalledWith(expect.objectContaining({ filter: { minRating: 4 } })),
+ );
+ });
+
+ it('filtrerer på alkohol og kan nullstilles', async () => {
+ const { user } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
+ const select = await screen.findByRole('combobox', { name: 'Alkohol' });
+ await user.selectOptions(select, 'high');
+ expect(location()).toHaveTextContent('/sok?alkohol=hoy');
+ await user.selectOptions(select, '');
+ expect(location()).toHaveTextContent(/^\/sok$/);
+ });
+
+ it('viser en rolig melding når filtrene ikke lastes, mens søket virker', async () => {
+ renderPage([searchMock(() => 3).mock, filterOptionsMock({ fails: true }).mock]);
+ expect(await screen.findByText('Vi fikk ikke hentet filtrene.')).toBeInTheDocument();
+ expect(await screen.findByRole('list', { name: 'Søkeresultater' })).toBeInTheDocument();
+ });
+
+ it('har ingen axe-brudd', async () => {
+ const { container } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
+ await screen.findByRole('checkbox', { name: /Rødvin/ });
+ await screen.findByRole('list', { name: 'Søkeresultater' });
+ expect(await axe(container)).toHaveNoViolations();
+ });
+});
+
+describe('Aktive filtre', () => {
+ beforeEach(() => setScreen(true));
+
+ it('viser valgene som lenker som fjerner ett filter', async () => {
+ renderPage(
+ [searchMock(() => 3).mock, filterOptionsMock().mock],
+ '/sok?q=pinot&type=rodvin&land=IT',
+ );
+ const active = await screen.findByRole('list', { name: 'Aktive filtre' });
+ expect(within(active).getByRole('link', { name: 'Fjern filteret Rødvin' })).toHaveAttribute(
+ 'href',
+ '/sok?q=pinot&land=IT',
+ );
+ expect(within(active).getByRole('link', { name: 'Fjern filteret Italia' })).toHaveAttribute(
+ 'href',
+ '/sok?q=pinot&type=rodvin',
+ );
+ });
+
+ it('viser vurdering og alkohol med forståelig tekst', async () => {
+ renderPage(
+ [searchMock(() => 3).mock, filterOptionsMock().mock],
+ '/sok?vurdering=3.5&alkohol=lav',
+ );
+ await screen.findByRole('list', { name: 'Søkeresultater' });
+ expect(
+ await screen.findByRole('link', { name: 'Fjern filteret Minst 3,5 av 5' }),
+ ).toBeInTheDocument();
+ });
+
+ it('kan nullstille alle filtre, men beholder søket og sorteringen', async () => {
+ renderPage(
+ [searchMock(() => 3).mock, filterOptionsMock().mock],
+ '/sok?q=pinot&type=rodvin&mat=Beef&sort=name',
+ );
+ expect(await screen.findByRole('link', { name: 'Nullstill filtre' })).toHaveAttribute(
+ 'href',
+ '/sok?q=pinot&sort=name',
+ );
+ });
+
+ it('vises ikke uten filtre', async () => {
+ renderPage([searchMock(() => 3).mock, filterOptionsMock().mock], '/sok?q=pinot');
+ await screen.findByRole('list', { name: 'Søkeresultater' });
+ expect(screen.queryByRole('list', { name: 'Aktive filtre' })).not.toBeInTheDocument();
+ });
+});
+
+describe('Sortering', () => {
+ beforeEach(() => setScreen(true));
+
+ it('sorterer hele resultatet via API-et og lagrer valget i URL-en', async () => {
+ const { mock, resolver } = searchMock(() => 3);
+ const { user } = renderPage([mock, filterOptionsMock().mock], '/sok?q=pinot');
+ await user.selectOptions(await screen.findByRole('combobox', { name: 'Sorter etter' }), 'name');
+
+ expect(location()).toHaveTextContent('/sok?q=pinot&sort=name');
+ await waitFor(() =>
+ expect(resolver).toHaveBeenCalledWith(expect.objectContaining({ sort: 'NAME_ASC' })),
+ );
+ });
+
+ it('viser valget fra URL-en', async () => {
+ renderPage([searchMock(() => 3).mock, filterOptionsMock().mock], '/sok?sort=reviews');
+ expect(await screen.findByRole('combobox', { name: 'Sorter etter' })).toHaveValue('reviews');
+ });
+
+ it('starter på best vurdert', async () => {
+ renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
+ expect(await screen.findByRole('combobox', { name: 'Sorter etter' })).toHaveValue('rating');
+ });
+
+ it('starter fra første side etter ny sortering', async () => {
+ const { mock, resolver } = searchMock(() => 3);
+ const { user } = renderPage([mock, filterOptionsMock().mock]);
+ await user.click(await screen.findByRole('button', { name: 'Last inn flere' }));
+ await screen.findByRole('link', { name: 'Vin 3' });
+ resolver.mockClear();
+
+ await user.selectOptions(screen.getByRole('combobox', { name: 'Sorter etter' }), 'name');
+
+ await waitFor(() => expect(resolver).toHaveBeenCalled());
+ expect(resolver.mock.calls[0][0].after).toBeUndefined();
+ });
+});
+
+describe('Filter på liten skjerm', () => {
+ beforeEach(() => {
+ setScreen(false);
+ HTMLDialogElement.prototype.showModal = function showModal() {
+ this.setAttribute('open', '');
+ };
+ HTMLDialogElement.prototype.close = function close() {
+ this.removeAttribute('open');
+ this.dispatchEvent(new Event('close'));
+ };
+ });
+
+ it('skjuler filtrene bak en knapp som viser antall valg', async () => {
+ renderPage(
+ [searchMock(() => 3).mock, filterOptionsMock().mock],
+ '/sok?type=rodvin&type=hvitvin',
+ );
+ expect(await screen.findByRole('button', { name: 'Filtrer (2 valgt)' })).toBeInTheDocument();
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ });
+
+ it('åpner filtrene i en dialog og oppdaterer søket underveis', async () => {
+ const { user } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
+ await user.click(await screen.findByRole('button', { name: 'Filtrer' }));
+
+ const dialog = screen.getByRole('dialog', { name: 'Filtrer' });
+ await user.click(await within(dialog).findByRole('checkbox', { name: /Rødvin/ }));
+
+ expect(location()).toHaveTextContent('/sok?type=rodvin');
+ expect(dialog).toBeInTheDocument();
+ });
+
+ it('lukker dialogen med knappen som viser antall treff', async () => {
+ const { user } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
+ await screen.findByRole('list', { name: 'Søkeresultater' });
+ await user.click(screen.getByRole('button', { name: 'Filtrer' }));
+
+ await user.click(screen.getByRole('button', { name: 'Vis 3 viner' }));
+
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ });
+
+ it('har ingen axe-brudd med åpen dialog', async () => {
+ const { user, container } = renderPage([searchMock(() => 3).mock, filterOptionsMock().mock]);
+ await user.click(await screen.findByRole('button', { name: 'Filtrer' }));
+ await screen.findByRole('checkbox', { name: /Rødvin/ });
+ expect(await axe(container)).toHaveNoViolations();
+ });
+});
diff --git a/frontend/src/features/search/SearchPage.tsx b/frontend/src/features/search/SearchPage.tsx
index 1c23872..a19000a 100644
--- a/frontend/src/features/search/SearchPage.tsx
+++ b/frontend/src/features/search/SearchPage.tsx
@@ -1,19 +1,36 @@
import { useSearchParams } from 'react-router';
import { useDocumentTitle } from '../../hooks/useDocumentTitle';
-import { parseSearchParams } from '../../lib/searchParams';
+import { parseSearchParams, toSearchParams, type SearchState } from '../../lib/searchParams';
+import { useFilterOptions } from './api/useFilterOptions';
import { useWineSearch } from './api/useWineSearch';
import { SearchView } from './SearchView';
import { useSearchText } from './useSearchText';
/** Route component for `/sok`. Connects the URL and the data to the presentation. */
export default function SearchPage() {
- const [params] = useSearchParams();
+ const [params, setParams] = useSearchParams();
const state = parseSearchParams(params);
const { text, setText, submit } = useSearchText();
const result = useWineSearch(state);
+ const filters = useFilterOptions(state);
useDocumentTitle(state.q ? `Søk: ${state.q}` : 'Utforsk viner');
+ // A new history entry for each choice, so the back button undoes the last filter.
+ const changeSearch = (changes: Partial) => {
+ setParams(toSearchParams({ ...state, ...changes }));
+ };
+
return (
-
+
);
}
diff --git a/frontend/src/features/search/SearchView.module.css b/frontend/src/features/search/SearchView.module.css
index cfa7ace..557a405 100644
--- a/frontend/src/features/search/SearchView.module.css
+++ b/frontend/src/features/search/SearchView.module.css
@@ -9,6 +9,63 @@
font-size: var(--text-2xl);
}
+.layout {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ gap: var(--space-5);
+}
+
+.filtersTitle {
+ margin-bottom: var(--space-3);
+ font-size: var(--text-lg);
+}
+
+.results {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+ align-content: start;
+ gap: var(--space-4);
+}
+
+.toolbar {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-2) var(--space-4);
+}
+
+.controls {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-3);
+}
+
+.sort {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2);
+}
+
+.sort select {
+ min-height: var(--tap-target);
+ padding: 0 var(--space-2);
+ border: 1px solid var(--color-text-muted);
+ border-radius: var(--radius-sm);
+ background: var(--color-surface);
+ color: var(--color-text);
+}
+
+/* Room for the filters beside the results, where the sidebar is rendered. */
+@media (min-width: 60rem) {
+ .layout {
+ grid-template-columns: 16rem minmax(0, 1fr);
+ gap: var(--space-6);
+ }
+}
+
/* The height is reserved so the list does not jump when the text changes. */
.status {
min-height: 1.5em;
diff --git a/frontend/src/features/search/SearchView.tsx b/frontend/src/features/search/SearchView.tsx
index 5d695e5..4dafb01 100644
--- a/frontend/src/features/search/SearchView.tsx
+++ b/frontend/src/features/search/SearchView.tsx
@@ -1,12 +1,22 @@
-import { useEffect, useRef } from 'react';
+import { useEffect, useRef, useId } from 'react';
import { Link } from 'react-router';
import { ErrorNotice } from '../../components/ui/ErrorNotice';
import { SearchForm } from '../../components/ui/SearchForm';
import { Skeleton } from '../../components/ui/Skeleton';
import { WineList } from '../../components/ui/WineList';
+import { useMediaQuery } from '../../hooks/useMediaQuery';
import { formatCount, pluralize } from '../../lib/format';
-import { buildSearchUrl } from '../../lib/searchParams';
+import {
+ activeFilterCount,
+ buildSearchUrl,
+ type SearchState,
+ type SortOption,
+} from '../../lib/searchParams';
+import type { FilterGroup } from './api/toFilterGroups';
import type { WineSearchResult } from './api/useWineSearch';
+import { ActiveFilters } from './components/ActiveFilters';
+import { FilterDialog } from './components/FilterDialog';
+import { FilterPanel } from './components/FilterPanel';
import styles from './SearchView.module.css';
type SearchViewProps = WineSearchResult & {
@@ -14,6 +24,17 @@ type SearchViewProps = WineSearchResult & {
text: string;
onTextChange: (text: string) => void;
onSubmit: () => void;
+ state: SearchState;
+ filterGroups: FilterGroup[];
+ filtersError: Error | undefined;
+ onChangeSearch: (changes: Partial) => void;
+};
+
+const SORT_LABELS: Record = {
+ rating: 'Best vurdert',
+ reviews: 'Flest vurderinger',
+ name: 'Navn A–Å',
+ alcohol: 'Høyest alkohol',
};
/** The text in the live region, which screen readers read when it changes (WCAG 4.1.3). */
@@ -39,6 +60,9 @@ export function SearchView(props: SearchViewProps) {
const { wines, totalCount, loading, error, loadMoreError, hasNextPage, loadMore, refetch } =
props;
const { query, text, onTextChange, onSubmit } = props;
+ const { state, filterGroups, filtersError, onChangeSearch } = props;
+ const sortId = useId();
+ const showSidebar = useMediaQuery('(min-width: 60rem)');
const listRef = useRef(null);
const firstNewWine = useRef(null);
@@ -58,6 +82,14 @@ export function SearchView(props: SearchViewProps) {
}
const noHits = !loading && !error && totalCount === 0;
+ const filterPanel = (
+
+ );
return (
@@ -71,41 +103,88 @@ export function SearchView(props: SearchViewProps) {
onSubmit={onSubmit}
/>
- {/* Always in the DOM, so changes are announced. */}
-
- {describeStatus(props)}
-
-
- {error &&
}
-
- {!error && loading && wines.length === 0 &&
}
-
- {!error && wines.length > 0 && (
-
-
-
- )}
-
- {noHits && (
-
-
- {query ? `Ingen viner passer til «${query}».` : 'Ingen viner passer til valgene dine.'}
-
-
Se alle viner
-
- )}
-
- {loadMoreError && (
-
- )}
-
- {hasNextPage && !loadMoreError && (
-
-
- Last inn flere
-
+
+ {showSidebar && (
+
+
+ Filtre
+
+ {filterPanel}
+
+ )}
+
+
+
+ {/* Always in the DOM, so changes are announced. */}
+
+ {describeStatus(props)}
+
+
+ {!showSidebar && (
+
+ {filterPanel}
+
+ )}
+
+ Sorter etter
+ onChangeSearch({ sort: event.target.value as SortOption })}
+ >
+ {(Object.keys(SORT_LABELS) as SortOption[]).map((sort) => (
+
+ {SORT_LABELS[sort]}
+
+ ))}
+
+
+
+
+
+
+
+ {error &&
}
+
+ {!error && loading && wines.length === 0 &&
}
+
+ {!error && wines.length > 0 && (
+
+
+
+ )}
+
+ {noHits && (
+
+
+ {query
+ ? `Ingen viner passer til «${query}».`
+ : 'Ingen viner passer til valgene dine.'}
+
+
Se alle viner
+
+ )}
+
+ {loadMoreError && (
+
+ )}
+
+ {hasNextPage && !loadMoreError && (
+
+
+ Last inn flere
+
+
+ )}
- )}
+
);
}
diff --git a/frontend/src/features/search/api/filterOptionsQuery.ts b/frontend/src/features/search/api/filterOptionsQuery.ts
new file mode 100644
index 0000000..7aa5441
--- /dev/null
+++ b/frontend/src/features/search/api/filterOptionsQuery.ts
@@ -0,0 +1,29 @@
+import { gql } from '@apollo/client';
+
+/** The values in the filter panel, with counts that follow the search and the other filters. */
+export const FILTER_OPTIONS_QUERY = gql`
+ query FilterOptions($search: String, $filter: WineFilter) {
+ filterOptions(search: $search, filter: $filter) {
+ types {
+ value
+ label
+ count
+ }
+ countries {
+ value
+ label
+ count
+ }
+ grapes {
+ value
+ label
+ count
+ }
+ harmonize {
+ value
+ label
+ count
+ }
+ }
+ }
+`;
diff --git a/frontend/src/features/search/api/searchQuery.ts b/frontend/src/features/search/api/searchQuery.ts
index 449a024..7acc65d 100644
--- a/frontend/src/features/search/api/searchQuery.ts
+++ b/frontend/src/features/search/api/searchQuery.ts
@@ -19,6 +19,7 @@ export const SEARCH_WINES_QUERY = gql`
type
grapes
country
+ countryCode
wineryName
communityRating
communityRatingCount
diff --git a/frontend/src/features/search/api/searchVariables.test.ts b/frontend/src/features/search/api/searchVariables.test.ts
index 58cd74e..170a227 100644
--- a/frontend/src/features/search/api/searchVariables.test.ts
+++ b/frontend/src/features/search/api/searchVariables.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { PAGE_SIZE, toSearchVariables } from './searchVariables';
+import { PAGE_SIZE, toFilterVariables, toSearchVariables } from './searchVariables';
describe('toSearchVariables', () => {
it('browses the whole catalogue for an empty search', () => {
@@ -12,26 +12,53 @@ describe('toSearchVariables', () => {
it('translates the URL filters to the API filter', () => {
expect(
- toSearchVariables({ type: 'FORTIFIED', country: 'IT', grape: 'Riesling', food: 'Pizza' })
- .filter,
+ toSearchVariables({
+ types: ['FORTIFIED', 'RED'],
+ countries: ['IT'],
+ grapes: ['Riesling'],
+ foods: ['Pizza'],
+ minRating: 4,
+ }).filter,
).toEqual({
- types: ['Dessert/Port'],
+ types: ['Dessert/Port', 'Red'],
countryCodes: ['IT'],
grapes: ['Riesling'],
harmonize: ['Pizza'],
+ minRating: 4,
});
});
it('only sends the filters that are set', () => {
- expect(toSearchVariables({ type: 'RED' }).filter).toEqual({ types: ['Red'] });
+ expect(toSearchVariables({ types: ['RED'] }).filter).toEqual({ types: ['Red'] });
+ });
+
+ it('sends no filter for empty lists', () => {
+ expect(toSearchVariables({ types: [] }).filter).toBeUndefined();
+ });
+
+ it.each([
+ ['low', { maxAbv: 11.9 }],
+ ['medium', { minAbv: 12, maxAbv: 14 }],
+ ['high', { minAbv: 14.1 }],
+ ] as const)('translates alcohol %s to a range without gaps', (alcohol, expected) => {
+ expect(toSearchVariables({ alcohol }).filter).toEqual(expected);
});
it.each([
- ['relevance', 'TOP_RATED'],
['rating', 'TOP_RATED'],
['reviews', 'MOST_RATED'],
['name', 'NAME_ASC'],
+ ['alcohol', 'ABV_DESC'],
] as const)('maps sort %s to %s', (sort, expected) => {
expect(toSearchVariables({ sort }).sort).toBe(expected);
});
});
+
+describe('toFilterVariables', () => {
+ it('sends the search and the filters, but no sorting or page size', () => {
+ expect(toFilterVariables({ q: 'pinot', types: ['RED'], sort: 'name' })).toEqual({
+ search: 'pinot',
+ filter: { types: ['Red'] },
+ });
+ });
+});
diff --git a/frontend/src/features/search/api/searchVariables.ts b/frontend/src/features/search/api/searchVariables.ts
index acc6a72..3a83dcc 100644
--- a/frontend/src/features/search/api/searchVariables.ts
+++ b/frontend/src/features/search/api/searchVariables.ts
@@ -1,52 +1,76 @@
import { toApiWineType } from '../../../lib/mapWine';
-import type { SearchState, SortOption } from '../../../lib/searchParams';
+import type { AlcoholLevel, 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';
+type ApiSort = 'TOP_RATED' | 'MOST_RATED' | 'NAME_ASC' | 'ABV_DESC';
-/** 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',
+ alcohol: 'ABV_DESC',
};
-export interface SearchVariables {
+/** The database stores alcohol with one decimal, so these ranges have no gaps. */
+const ALCOHOL_RANGES: Record = {
+ low: { maxAbv: 11.9 },
+ medium: { minAbv: 12, maxAbv: 14 },
+ high: { minAbv: 14.1 },
+};
+
+export interface ApiWineFilter {
+ types?: string[];
+ countryCodes?: string[];
+ grapes?: string[];
+ harmonize?: string[];
+ minRating?: number;
+ minAbv?: number;
+ maxAbv?: number;
+}
+
+export interface FilterVariables {
search?: string;
- filter?: {
- types?: string[];
- countryCodes?: string[];
- grapes?: string[];
- harmonize?: string[];
- };
+ filter?: ApiWineFilter;
+}
+
+export interface SearchVariables extends FilterVariables {
sort: ApiSort;
first: number;
after?: string;
}
-/** Translates the search state from the URL to variables for SEARCH_WINES_QUERY. */
-export function toSearchVariables({
+/** The search and filters from the URL as variables, for both the results and the counts. */
+export function toFilterVariables({
q,
- type,
- country,
- grape,
- food,
- sort = 'relevance',
-}: SearchState): SearchVariables {
- const filter = {
- ...(type && { types: [toApiWineType(type)] }),
- ...(country && { countryCodes: [country] }),
- ...(grape && { grapes: [grape] }),
- ...(food && { harmonize: [food] }),
+ types = [],
+ countries = [],
+ grapes = [],
+ foods = [],
+ minRating,
+ alcohol,
+}: SearchState): FilterVariables {
+ const filter: ApiWineFilter = {
+ ...(types.length > 0 && { types: types.map(toApiWineType) }),
+ ...(countries.length > 0 && { countryCodes: countries }),
+ ...(grapes.length > 0 && { grapes }),
+ ...(foods.length > 0 && { harmonize: foods }),
+ ...(minRating && { minRating }),
+ ...(alcohol && ALCOHOL_RANGES[alcohol]),
};
return {
...(q && { search: q }),
...(Object.keys(filter).length > 0 && { filter }),
- sort: API_SORT[sort],
+ };
+}
+
+/** Translates the search state from the URL to variables for SEARCH_WINES_QUERY. */
+export function toSearchVariables(state: SearchState): SearchVariables {
+ return {
+ ...toFilterVariables(state),
+ sort: API_SORT[state.sort ?? 'rating'],
first: PAGE_SIZE,
};
}
diff --git a/frontend/src/features/search/api/toFilterGroups.test.ts b/frontend/src/features/search/api/toFilterGroups.test.ts
new file mode 100644
index 0000000..1f658ac
--- /dev/null
+++ b/frontend/src/features/search/api/toFilterGroups.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest';
+import { toFilterGroups, type FilterOptionsData } from './toFilterGroups';
+
+const data: FilterOptionsData = {
+ filterOptions: {
+ types: [
+ { value: 'White', label: 'White', count: 19 },
+ { value: 'Red', label: 'Red', count: 53 },
+ { value: 'Orange', label: 'Orange', count: 2 },
+ ],
+ countries: [{ value: 'IT', label: 'Italy', count: 25 }],
+ grapes: [{ value: 'Merlot', label: 'Merlot', count: 9 }],
+ harmonize: [{ value: 'Beef', label: 'Beef', count: 53 }],
+ },
+};
+
+const options = (state = {}) => {
+ const groups = toFilterGroups(data, state);
+ return Object.fromEntries(groups.map((group) => [group.key, group.options]));
+};
+
+describe('toFilterGroups', () => {
+ it('has the groups in the order they are shown', () => {
+ expect(toFilterGroups(data, {}).map((group) => group.legend)).toEqual([
+ 'Type',
+ 'Land',
+ 'Drue',
+ 'Passer til',
+ ]);
+ });
+
+ it('shows the wine types in a fixed order and leaves out unknown types', () => {
+ expect(options().types).toEqual([
+ { value: 'RED', label: 'Rødvin', count: 53, selected: false },
+ { value: 'WHITE', label: 'Hvitvin', count: 19, selected: false },
+ ]);
+ });
+
+ it('shows countries and food in Norwegian, and keeps the API value', () => {
+ expect(options().countries[0]).toMatchObject({ value: 'IT', label: 'Italia' });
+ expect(options().foods[0]).toMatchObject({ value: 'Beef', label: 'Storfe' });
+ });
+
+ it('marks what is selected', () => {
+ expect(options({ grapes: ['Merlot'] }).grapes[0].selected).toBe(true);
+ });
+
+ it('keeps a selected value with no hits, so the user can remove it', () => {
+ const { countries } = options({ countries: ['FR'] });
+ expect(countries[0]).toEqual({ value: 'FR', label: 'Frankrike', count: 0, selected: true });
+ expect(countries).toHaveLength(2);
+ });
+
+ it('keeps a selected wine type with no hits', () => {
+ expect(options({ types: ['SPARKLING'] }).types.at(-1)).toEqual({
+ value: 'SPARKLING',
+ label: 'Musserende',
+ count: 0,
+ selected: true,
+ });
+ });
+
+ it('gives empty groups before the first response', () => {
+ expect(toFilterGroups(undefined, { grapes: ['Merlot'] })[2].options).toEqual([
+ { value: 'Merlot', label: 'Merlot', count: 0, selected: true },
+ ]);
+ });
+});
diff --git a/frontend/src/features/search/api/toFilterGroups.ts b/frontend/src/features/search/api/toFilterGroups.ts
new file mode 100644
index 0000000..5ea57ce
--- /dev/null
+++ b/frontend/src/features/search/api/toFilterGroups.ts
@@ -0,0 +1,110 @@
+import { formatCountry } from '../../../lib/format';
+import { toWineType } from '../../../lib/mapWine';
+import type { SearchState } from '../../../lib/searchParams';
+import type { WineType } from '../../../lib/types';
+import { foodLabel } from '../../../lib/wineLabels';
+import { WINE_TYPE_ORDER, WINE_TYPES } from '../../../lib/wineTypes';
+
+interface ApiFilterOption {
+ value: string;
+ label: string;
+ count: number;
+}
+
+/** The response from FILTER_OPTIONS_QUERY. */
+export interface FilterOptionsData {
+ filterOptions: {
+ types: ApiFilterOption[];
+ countries: ApiFilterOption[];
+ grapes: ApiFilterOption[];
+ harmonize: ApiFilterOption[];
+ };
+}
+
+export interface FilterOption {
+ /** What goes in the URL. */
+ value: string;
+ label: string;
+ count: number;
+ selected: boolean;
+}
+
+export type FilterKey = 'types' | 'countries' | 'grapes' | 'foods';
+
+export interface FilterGroup {
+ key: FilterKey;
+ legend: string;
+ options: FilterOption[];
+}
+
+/**
+ * Marks what is selected. A selected value with no hits is missing from the API response,
+ * but it must stay in the list, or the user could not remove it again.
+ */
+function withSelected(
+ options: Omit[],
+ selected: string[] = [],
+ labelOf: (value: string) => string,
+): FilterOption[] {
+ const known = new Set(options.map((option) => option.value));
+ const missing = selected
+ .filter((value) => !known.has(value))
+ .map((value) => ({ value, label: labelOf(value), count: 0 }));
+
+ return [...missing, ...options].map((option) => ({
+ ...option,
+ selected: selected.includes(option.value),
+ }));
+}
+
+function typeOptions(types: ApiFilterOption[] = [], selected: WineType[] = []): FilterOption[] {
+ const counts = new Map(types.map(({ value, count }) => [toWineType(value), count]));
+ const visible = WINE_TYPE_ORDER.filter((type) => counts.has(type) || selected.includes(type));
+
+ return visible.map((type) => ({
+ value: type,
+ label: WINE_TYPES[type].label,
+ count: counts.get(type) ?? 0,
+ selected: selected.includes(type),
+ }));
+}
+
+/** Builds the groups in the filter panel from the API response and the search state. */
+export function toFilterGroups(
+ data: FilterOptionsData | undefined,
+ state: SearchState,
+): FilterGroup[] {
+ const { types, countries = [], grapes = [], harmonize = [] } = data?.filterOptions ?? {};
+ const countryName = (code: string, fallback = code) => formatCountry(code, fallback);
+
+ return [
+ { key: 'types', legend: 'Type', options: typeOptions(types, state.types) },
+ {
+ key: 'countries',
+ legend: 'Land',
+ options: withSelected(
+ countries.map(({ value, label, count }) => ({
+ value,
+ label: countryName(value, label),
+ count,
+ })),
+ state.countries,
+ countryName,
+ ),
+ },
+ {
+ key: 'grapes',
+ legend: 'Drue',
+ options: withSelected(grapes, state.grapes, (value) => value),
+ },
+ {
+ key: 'foods',
+ legend: 'Passer til',
+ options: withSelected(
+ harmonize.map(({ value, count }) => ({ value, label: foodLabel(value), count })),
+ state.foods,
+ foodLabel,
+ ),
+ },
+ ];
+}
diff --git a/frontend/src/features/search/api/useFilterOptions.ts b/frontend/src/features/search/api/useFilterOptions.ts
new file mode 100644
index 0000000..bc1c382
--- /dev/null
+++ b/frontend/src/features/search/api/useFilterOptions.ts
@@ -0,0 +1,20 @@
+import { useQuery } from '@apollo/client/react';
+import type { SearchState } from '../../../lib/searchParams';
+import { FILTER_OPTIONS_QUERY } from './filterOptionsQuery';
+import { toFilterVariables, type FilterVariables } from './searchVariables';
+import { toFilterGroups, type FilterGroup, type FilterOptionsData } from './toFilterGroups';
+
+export interface FilterOptionsResult {
+ groups: FilterGroup[];
+ error: Error | undefined;
+}
+
+/** The old counts stay until the new ones arrive, so the panel does not jump between choices. */
+export function useFilterOptions(state: SearchState): FilterOptionsResult {
+ const { data, previousData, error } = useQuery(
+ FILTER_OPTIONS_QUERY,
+ { variables: toFilterVariables(state) },
+ );
+
+ return { groups: toFilterGroups(data ?? previousData, state), error };
+}
diff --git a/frontend/src/features/search/components/ActiveFilters.module.css b/frontend/src/features/search/components/ActiveFilters.module.css
new file mode 100644
index 0000000..7bee058
--- /dev/null
+++ b/frontend/src/features/search/components/ActiveFilters.module.css
@@ -0,0 +1,16 @@
+.active {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2) var(--space-3);
+}
+
+.list {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ min-width: 0;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
diff --git a/frontend/src/features/search/components/ActiveFilters.tsx b/frontend/src/features/search/components/ActiveFilters.tsx
new file mode 100644
index 0000000..14ee1d9
--- /dev/null
+++ b/frontend/src/features/search/components/ActiveFilters.tsx
@@ -0,0 +1,51 @@
+import { Link } from 'react-router';
+import { ChipLink } from '../../../components/ui/Chip';
+import { buildSearchUrl, toggleValue, type SearchState } from '../../../lib/searchParams';
+import type { FilterGroup } from '../api/toFilterGroups';
+import { ALCOHOL_LABELS, ratingLabel } from '../filterLabels';
+import styles from './ActiveFilters.module.css';
+
+interface ActiveFiltersProps {
+ state: SearchState;
+ groups: FilterGroup[];
+}
+
+/** The selected filters as links, since removing one changes the URL. */
+export function ActiveFilters({ state, groups }: ActiveFiltersProps) {
+ const chips = [
+ ...groups.flatMap(({ key, options }) =>
+ options
+ .filter((option) => option.selected)
+ .map((option) => ({
+ label: option.label,
+ without: { [key]: toggleValue(state[key] as string[], option.value) },
+ })),
+ ),
+ ...(state.minRating
+ ? [{ label: ratingLabel(state.minRating), without: { minRating: undefined } }]
+ : []),
+ ...(state.alcohol
+ ? [{ label: ALCOHOL_LABELS[state.alcohol], without: { alcohol: undefined } }]
+ : []),
+ ];
+
+ if (chips.length === 0) return null;
+
+ return (
+
+
+ {chips.map(({ label, without }) => (
+
+
+ {label} ×
+
+
+ ))}
+
+
Nullstill filtre
+
+ );
+}
diff --git a/frontend/src/features/search/components/FilterDialog.module.css b/frontend/src/features/search/components/FilterDialog.module.css
new file mode 100644
index 0000000..f2ef003
--- /dev/null
+++ b/frontend/src/features/search/components/FilterDialog.module.css
@@ -0,0 +1,68 @@
+.open {
+ min-height: var(--tap-target);
+ padding: 0 var(--space-4);
+ border: 2px solid var(--color-link);
+ border-radius: var(--radius-pill);
+ background: transparent;
+ color: var(--color-text);
+ font-weight: 700;
+ cursor: pointer;
+}
+
+.dialog {
+ width: 100%;
+ max-width: 100%;
+ height: 100%;
+ max-height: 100%;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ background: var(--color-bg);
+ color: var(--color-text);
+}
+
+/* The header and the button stay in place while the filters scroll. */
+.dialog[open] {
+ display: grid;
+ grid-template-rows: auto minmax(0, 1fr) auto;
+}
+
+.header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-3);
+ padding: var(--space-3) var(--space-4);
+ border-bottom: 1px solid var(--color-border);
+}
+
+.dismiss {
+ min-height: var(--tap-target);
+ padding: 0 var(--space-3);
+ border: 0;
+ background: transparent;
+ color: var(--color-link);
+ text-decoration: underline;
+ cursor: pointer;
+}
+
+.body {
+ padding: var(--space-4);
+ overflow-y: auto;
+}
+
+.footer {
+ padding: var(--space-3) var(--space-4);
+ border-top: 1px solid var(--color-border);
+}
+
+.apply {
+ width: 100%;
+ min-height: var(--tap-target);
+ border: 0;
+ border-radius: var(--radius-pill);
+ background: var(--color-brand);
+ color: var(--color-on-brand);
+ font-weight: 700;
+ cursor: pointer;
+}
diff --git a/frontend/src/features/search/components/FilterDialog.tsx b/frontend/src/features/search/components/FilterDialog.tsx
new file mode 100644
index 0000000..a12ea5b
--- /dev/null
+++ b/frontend/src/features/search/components/FilterDialog.tsx
@@ -0,0 +1,60 @@
+import { useEffect, useId, useRef, useState, type ReactNode } from 'react';
+import styles from './FilterDialog.module.css';
+
+interface FilterDialogProps {
+ activeCount: number;
+ /** The text on the closing button, for example «Vis 12 viner». */
+ closeLabel: string;
+ children: ReactNode;
+}
+
+/**
+ * The filters on small screens. A native modal dialog traps focus, closes with
+ * Escape and gives focus back to the button, so that does not have to be built by hand.
+ */
+export function FilterDialog({ activeCount, closeLabel, children }: FilterDialogProps) {
+ const titleId = useId();
+ const dialogRef = useRef(null);
+ const [open, setOpen] = useState(false);
+
+ useEffect(() => {
+ if (open) dialogRef.current?.showModal();
+ }, [open]);
+
+ const close = () => dialogRef.current?.close();
+
+ return (
+ <>
+ setOpen(true)}
+ >
+ Filtrer{activeCount > 0 && ` (${activeCount} valgt)`}
+
+
+ {open && (
+ setOpen(false)}
+ >
+
+
Filtrer
+
+ Lukk
+
+
+ {children}
+
+
+ {closeLabel}
+
+
+
+ )}
+ >
+ );
+}
diff --git a/frontend/src/features/search/components/FilterPanel.module.css b/frontend/src/features/search/components/FilterPanel.module.css
new file mode 100644
index 0000000..7eceffa
--- /dev/null
+++ b/frontend/src/features/search/components/FilterPanel.module.css
@@ -0,0 +1,76 @@
+.panel {
+ display: grid;
+ gap: var(--space-5);
+}
+
+.error {
+ font-size: var(--text-sm);
+ color: var(--color-text-muted);
+}
+
+.group {
+ min-width: 0;
+ margin: 0;
+ padding: 0;
+ border: 0;
+}
+
+.legend {
+ display: block;
+ margin-bottom: var(--space-2);
+ padding: 0;
+ font-weight: 700;
+}
+
+.options {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.option {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ min-height: var(--tap-target);
+ cursor: pointer;
+}
+
+.option input {
+ flex: none;
+ width: 1.25rem;
+ height: 1.25rem;
+ margin: 0;
+ accent-color: var(--color-brand);
+}
+
+.optionLabel {
+ flex: 1;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+
+.count {
+ font-size: var(--text-sm);
+ color: var(--color-text-muted);
+}
+
+.expand {
+ min-height: var(--tap-target);
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: var(--color-link);
+ text-decoration: underline;
+ cursor: pointer;
+}
+
+.select select {
+ width: 100%;
+ min-height: var(--tap-target);
+ padding: 0 var(--space-2);
+ border: 1px solid var(--color-text-muted);
+ border-radius: var(--radius-sm);
+ background: var(--color-surface);
+ color: var(--color-text);
+}
diff --git a/frontend/src/features/search/components/FilterPanel.tsx b/frontend/src/features/search/components/FilterPanel.tsx
new file mode 100644
index 0000000..c9a1e0c
--- /dev/null
+++ b/frontend/src/features/search/components/FilterPanel.tsx
@@ -0,0 +1,132 @@
+import { useId, useState, type ChangeEvent } from 'react';
+import { pluralize } from '../../../lib/format';
+import {
+ RATING_OPTIONS,
+ toggleValue,
+ type AlcoholLevel,
+ type SearchState,
+} from '../../../lib/searchParams';
+import type { FilterGroup as Group } from '../api/toFilterGroups';
+import { ALCOHOL_LABELS, ratingLabel } from '../filterLabels';
+import styles from './FilterPanel.module.css';
+
+/** The number of values shown in a group before "Vis alle". */
+const COLLAPSED_COUNT = 6;
+
+interface FilterPanelProps {
+ state: SearchState;
+ groups: Group[];
+ error: Error | undefined;
+ onChange: (changes: Partial) => void;
+}
+
+/** The filters themselves. The same panel is used in the sidebar and in the mobile dialog. */
+export function FilterPanel({ state, groups, error, onChange }: FilterPanelProps) {
+ return (
+
+ {error &&
Vi fikk ikke hentet filtrene.
}
+
+ {groups.map((group) =>
+ group.options.length > 0 ? (
+
+ onChange({ [group.key]: toggleValue(state[group.key] as string[], value) })
+ }
+ />
+ ) : null,
+ )}
+
+ onChange({ minRating: Number(event.target.value) || undefined })}
+ >
+ Alle vurderinger
+ {RATING_OPTIONS.map((rating) => (
+
+ {ratingLabel(rating)}
+
+ ))}
+
+
+
+ onChange({ alcohol: (event.target.value as AlcoholLevel) || undefined })
+ }
+ >
+ Alle styrker
+ {(Object.keys(ALCOHOL_LABELS) as AlcoholLevel[]).map((level) => (
+
+ {ALCOHOL_LABELS[level]}
+
+ ))}
+
+
+ );
+}
+
+function FilterGroup({ group, onToggle }: { group: Group; onToggle: (value: string) => void }) {
+ const [expanded, setExpanded] = useState(false);
+ const { legend, options } = group;
+ // A selected value is always visible, so what filters the result can never be hidden.
+ const visible = expanded
+ ? options
+ : options.filter((option, index) => index < COLLAPSED_COUNT || option.selected);
+
+ return (
+
+ {legend}
+
+ {options.length > COLLAPSED_COUNT && (
+ setExpanded(!expanded)}
+ >
+ {expanded ? `Vis færre i ${legend}` : `Vis alle i ${legend} (${options.length})`}
+
+ )}
+
+ );
+}
+
+interface SelectFilterProps {
+ label: string;
+ value: string;
+ onChange: (event: ChangeEvent) => void;
+ children: React.ReactNode;
+}
+
+function SelectFilter({ label, value, onChange, children }: SelectFilterProps) {
+ const id = useId();
+ return (
+
+
+ {label}
+
+
+ {children}
+
+
+ );
+}
diff --git a/frontend/src/features/search/filterLabels.ts b/frontend/src/features/search/filterLabels.ts
new file mode 100644
index 0000000..673be52
--- /dev/null
+++ b/frontend/src/features/search/filterLabels.ts
@@ -0,0 +1,10 @@
+import { formatRating } from '../../lib/format';
+import type { AlcoholLevel } from '../../lib/searchParams';
+
+export const ALCOHOL_LABELS: Record = {
+ low: 'Under 12 %',
+ medium: '12–14 %',
+ high: 'Over 14 %',
+};
+
+export const ratingLabel = (rating: number) => `Minst ${formatRating(rating)} av 5`;
diff --git a/frontend/src/features/wine/WineView.tsx b/frontend/src/features/wine/WineView.tsx
index 9d40f0f..a087a8d 100644
--- a/frontend/src/features/wine/WineView.tsx
+++ b/frontend/src/features/wine/WineView.tsx
@@ -117,7 +117,7 @@ function WineDetailsView({ wine }: { wine: WineDetails }) {
{wine.grapes.map((grape, index) => (
{index > 0 && ', '}
- {grape}
+ {grape}
))}
@@ -136,7 +136,7 @@ function WineDetailsView({ wine }: { wine: WineDetails }) {
{wine.foods.map((food) => (
- {food.label}
+ {food.label}
))}
diff --git a/frontend/src/features/wine/api/toWineDetails.ts b/frontend/src/features/wine/api/toWineDetails.ts
index b8410ea..d1ff4d9 100644
--- a/frontend/src/features/wine/api/toWineDetails.ts
+++ b/frontend/src/features/wine/api/toWineDetails.ts
@@ -1,11 +1,9 @@
-import { formatCountry } from '../../../lib/format';
import { toWineSummary, type ApiWine } from '../../../lib/mapWine';
import type { WineDetails } from '../../../lib/types';
import { acidityLabel, bodyLabel, foodLabel, styleLabel } from '../../../lib/wineLabels';
/** The wine fields WINE_QUERY reads from the API. */
export interface ApiWineDetails extends ApiWine {
- countryCode: string | null;
regionName: string | null;
website: string | null;
elaborate: string | null;
@@ -34,7 +32,6 @@ export function toWineDetails(wine: ApiWineDetails): WineDetails | null {
return {
...summary,
- country: wine.countryCode ? formatCountry(wine.countryCode, summary.country) : summary.country,
region: wine.regionName,
abv: wine.abv,
body: wine.body && bodyLabel(wine.body),
diff --git a/frontend/src/hooks/useMediaQuery.ts b/frontend/src/hooks/useMediaQuery.ts
new file mode 100644
index 0000000..41ade6a
--- /dev/null
+++ b/frontend/src/hooks/useMediaQuery.ts
@@ -0,0 +1,15 @@
+import { useCallback, useSyncExternalStore } from 'react';
+
+/** True while a CSS media query matches, for layouts that differ in the DOM and not only in CSS. */
+export function useMediaQuery(query: string): boolean {
+ const subscribe = useCallback(
+ (onChange: () => void) => {
+ const media = window.matchMedia?.(query);
+ media?.addEventListener('change', onChange);
+ return () => media?.removeEventListener('change', onChange);
+ },
+ [query],
+ );
+
+ return useSyncExternalStore(subscribe, () => window.matchMedia?.(query).matches ?? false);
+}
diff --git a/frontend/src/lib/apollo.ts b/frontend/src/lib/apollo.ts
index 523b4be..f4d872d 100644
--- a/frontend/src/lib/apollo.ts
+++ b/frontend/src/lib/apollo.ts
@@ -29,6 +29,8 @@ export function mergeWineConnection(
export function createApolloCache() {
return new InMemoryCache({
typePolicies: {
+ // The landing page and the search page ask for different groups of the same object.
+ FilterOptions: { merge: true },
Query: {
fields: {
wines: {
diff --git a/frontend/src/lib/mapWine.test.ts b/frontend/src/lib/mapWine.test.ts
index 5b0a579..caa0f3b 100644
--- a/frontend/src/lib/mapWine.test.ts
+++ b/frontend/src/lib/mapWine.test.ts
@@ -7,6 +7,7 @@ const apiWine: ApiWine = {
type: 'Red',
grapes: ['Pinot Noir'],
country: 'United States',
+ countryCode: 'US',
wineryName: 'Domaine Drouhin',
communityRating: 4.88,
communityRatingCount: 8,
@@ -46,7 +47,7 @@ describe('toWineSummary', () => {
name: 'Lauréne Pinot Noir',
type: 'RED',
grapes: ['Pinot Noir'],
- country: 'United States',
+ country: 'USA',
winery: 'Domaine Drouhin',
community: { average: 4.88, count: 8 },
students: null,
@@ -54,7 +55,12 @@ describe('toWineSummary', () => {
});
it('uses readable text when country and winery are missing', () => {
- const wine = toWineSummary({ ...apiWine, country: null, wineryName: null });
+ const wine = toWineSummary({
+ ...apiWine,
+ country: null,
+ countryCode: null,
+ wineryName: null,
+ });
expect(wine?.country).toBe('Ukjent land');
expect(wine?.winery).toBe('Ukjent produsent');
});
diff --git a/frontend/src/lib/mapWine.ts b/frontend/src/lib/mapWine.ts
index 6c9c051..955d879 100644
--- a/frontend/src/lib/mapWine.ts
+++ b/frontend/src/lib/mapWine.ts
@@ -1,3 +1,4 @@
+import { formatCountry } from './format';
import type { WineSummary, WineType } from './types';
/** The wine fields the frontend reads from the GraphQL API. */
@@ -7,6 +8,7 @@ export interface ApiWine {
type: string;
grapes: string[];
country: string | null;
+ countryCode: string | null;
wineryName: string | null;
communityRating: number | null;
communityRatingCount: number;
@@ -44,7 +46,9 @@ export function toWineSummary(wine: ApiWine): WineSummary | null {
name: wine.name,
type,
grapes: wine.grapes,
- country: wine.country ?? 'Ukjent land',
+ country: wine.countryCode
+ ? formatCountry(wine.countryCode, wine.country ?? 'Ukjent land')
+ : (wine.country ?? 'Ukjent land'),
winery: wine.wineryName ?? 'Ukjent produsent',
community: { average: wine.communityRating, count: wine.communityRatingCount },
students: null, // The API has no student reviews yet.
diff --git a/frontend/src/lib/searchParams.test.ts b/frontend/src/lib/searchParams.test.ts
index 76b796e..829df35 100644
--- a/frontend/src/lib/searchParams.test.ts
+++ b/frontend/src/lib/searchParams.test.ts
@@ -1,10 +1,18 @@
import { describe, expect, it } from 'vitest';
-import { buildSearchUrl, parseSearchParams, toSearchParams } from './searchParams';
+import {
+ activeFilterCount,
+ buildSearchUrl,
+ parseSearchParams,
+ toggleValue,
+ toSearchParams,
+ type SearchState,
+} from './searchParams';
describe('buildSearchUrl', () => {
it('gir /sok uten parametere når tilstanden er tom', () => {
expect(buildSearchUrl()).toBe('/sok');
expect(buildSearchUrl({ q: ' ' })).toBe('/sok');
+ expect(buildSearchUrl({ types: [], grapes: [] })).toBe('/sok');
});
it('trimmer og slår sammen mellomrom i fritekst', () => {
@@ -12,19 +20,30 @@ describe('buildSearchUrl', () => {
});
it('bruker norske slugs for vintype', () => {
- expect(buildSearchUrl({ type: 'RED' })).toBe('/sok?type=rodvin');
- expect(buildSearchUrl({ type: 'ROSE' })).toBe('/sok?type=rose');
+ expect(buildSearchUrl({ types: ['RED'] })).toBe('/sok?type=rodvin');
+ expect(buildSearchUrl({ types: ['ROSE'] })).toBe('/sok?type=rose');
});
- it('har fast rekkefølge på parametere uavhengig av input', () => {
- expect(buildSearchUrl({ food: 'Pizza', q: 'chianti', country: 'Italia', type: 'RED' })).toBe(
- '/sok?q=chianti&type=rodvin&land=Italia&mat=Pizza',
+ it('gjentar parameteren når flere verdier er valgt', () => {
+ expect(buildSearchUrl({ countries: ['IT', 'FR'] })).toBe('/sok?land=FR&land=IT');
+ });
+
+ it('gir samme URL uansett rekkefølgen brukeren valgte i', () => {
+ expect(buildSearchUrl({ types: ['WHITE', 'RED'] })).toBe(
+ buildSearchUrl({ types: ['RED', 'WHITE'] }),
);
});
- it('utelater standardsortering, men tar med andre', () => {
- expect(buildSearchUrl({ sort: 'relevance' })).toBe('/sok');
- expect(buildSearchUrl({ sort: 'rating' })).toBe('/sok?sort=rating');
+ it('har fast rekkefølge på parametere uavhengig av input', () => {
+ expect(
+ buildSearchUrl({ foods: ['Pizza'], q: 'chianti', countries: ['IT'], types: ['RED'] }),
+ ).toBe('/sok?q=chianti&type=rodvin&land=IT&mat=Pizza');
+ });
+
+ it('tar med minimumsvurdering, alkohol og sortering', () => {
+ expect(buildSearchUrl({ minRating: 4, alcohol: 'high', sort: 'name' })).toBe(
+ '/sok?vurdering=4&alkohol=hoy&sort=name',
+ );
});
it('koder spesialtegn', () => {
@@ -34,22 +53,68 @@ describe('buildSearchUrl', () => {
describe('parseSearchParams', () => {
it('er den omvendte av toSearchParams', () => {
- const state = {
+ const state: SearchState = {
q: 'riesling',
- type: 'WHITE',
- country: 'Tyskland',
- grape: 'Riesling',
- food: 'Fisk',
+ types: ['RED', 'WHITE'],
+ countries: ['DE'],
+ grapes: ['Riesling'],
+ foods: ['Fish'],
+ minRating: 3.5,
+ alcohol: 'low',
sort: 'rating',
- } as const;
+ };
expect(parseSearchParams(toSearchParams(state))).toEqual(state);
});
- it('ignorerer ukjente vintyper og sorteringer', () => {
- expect(parseSearchParams(new URLSearchParams('type=oel&sort=pris'))).toEqual({});
+ it('ignorerer ukjente verdier', () => {
+ expect(
+ parseSearchParams(new URLSearchParams('type=oel&sort=pris&vurdering=9&alkohol=mye')),
+ ).toEqual({});
+ });
+
+ it('beholder gyldige verdier når en annen er ugyldig', () => {
+ expect(parseSearchParams(new URLSearchParams('type=oel&type=rodvin'))).toEqual({
+ types: ['RED'],
+ });
+ });
+
+ it('fjerner dubletter', () => {
+ expect(parseSearchParams(new URLSearchParams('land=IT&land=IT'))).toEqual({
+ countries: ['IT'],
+ });
});
it('ignorerer tomme verdier', () => {
expect(parseSearchParams(new URLSearchParams('q=%20&land='))).toEqual({});
});
});
+
+describe('toggleValue', () => {
+ it('legger til en verdi som ikke er valgt', () => {
+ expect(toggleValue(['A'], 'B')).toEqual(['A', 'B']);
+ expect(toggleValue(undefined, 'A')).toEqual(['A']);
+ });
+
+ it('fjerner en verdi som er valgt', () => {
+ expect(toggleValue(['A', 'B'], 'A')).toEqual(['B']);
+ });
+});
+
+describe('activeFilterCount', () => {
+ it('teller hver valgte verdi, men ikke søkeord og sortering', () => {
+ expect(
+ activeFilterCount({
+ q: 'pinot',
+ sort: 'name',
+ types: ['RED', 'WHITE'],
+ foods: ['Pizza'],
+ minRating: 4,
+ alcohol: 'low',
+ }),
+ ).toBe(5);
+ });
+
+ it('er null uten filtre', () => {
+ expect(activeFilterCount({ q: 'pinot' })).toBe(0);
+ });
+});
diff --git a/frontend/src/lib/searchParams.ts b/frontend/src/lib/searchParams.ts
index a19feee..f7e3379 100644
--- a/frontend/src/lib/searchParams.ts
+++ b/frontend/src/lib/searchParams.ts
@@ -1,67 +1,131 @@
import type { WineType } from './types';
-import { WINE_TYPES, wineTypeFromSlug } from './wineTypes';
+import { WINE_TYPE_ORDER, WINE_TYPES, wineTypeFromSlug } from './wineTypes';
/**
- * Søketilstanden lever i URL-en (sannhetskilden), slik at den overlever
- * reload, kan deles og fungerer med tilbakeknappen.
+ * The search state lives in the URL, which is the source of truth, so it survives
+ * a reload, can be shared and works with the back button.
*
- * Søkesiden skal bruke `parseSearchParams` og samme parameternavn.
+ * Always read it with `parseSearchParams` and build links with `buildSearchUrl`.
*/
export const SEARCH_PATH = '/sok';
-export type SortOption = 'relevance' | 'rating' | 'reviews' | 'name';
+export type SortOption = 'rating' | 'reviews' | 'name' | 'alcohol';
+export type AlcoholLevel = 'low' | 'medium' | 'high';
export interface SearchState {
q?: string;
- type?: WineType;
- country?: string;
- grape?: string;
- /** Matparing, f.eks. «Pizza». Matcher `harmonize` i X-Wines. */
- food?: string;
+ types?: WineType[];
+ /** Country codes, for example `IT`. */
+ countries?: string[];
+ grapes?: string[];
+ /** Food pairings as the API names them, for example `Pizza`. Match `harmonize` in X-Wines. */
+ foods?: string[];
+ minRating?: number;
+ alcohol?: AlcoholLevel;
sort?: SortOption;
}
-/** Fast rekkefølge gir stabile, delbare URL-er og forutsigbare tester. */
-const PARAM_ORDER = ['q', 'type', 'land', 'drue', 'mat', 'sort'] as const;
+export const RATING_OPTIONS = [3, 3.5, 4, 4.5];
-const SORT_OPTIONS: SortOption[] = ['relevance', 'rating', 'reviews', 'name'];
+const SORT_OPTIONS: SortOption[] = ['rating', 'reviews', 'name', 'alcohol'];
+
+const ALCOHOL_SLUGS: Record = {
+ low: 'lav',
+ medium: 'middels',
+ high: 'hoy',
+};
+
+/** Selected values in a fixed order give stable URLs, whatever order the user clicked in. */
+function sortedTypes(types: WineType[] = []): WineType[] {
+ return WINE_TYPE_ORDER.filter((type) => types.includes(type));
+}
export function toSearchParams(state: SearchState): URLSearchParams {
- const raw: Record<(typeof PARAM_ORDER)[number], string | undefined> = {
- q: state.q?.trim().replace(/\s+/g, ' '),
- type: state.type ? WINE_TYPES[state.type].slug : undefined,
- land: state.country?.trim(),
- drue: state.grape?.trim(),
- mat: state.food?.trim(),
- sort: state.sort && state.sort !== 'relevance' ? state.sort : undefined,
- };
const params = new URLSearchParams();
- for (const key of PARAM_ORDER) {
- const value = raw[key];
- if (value) params.set(key, value);
- }
+ const add = (key: string, values: (string | undefined)[]) => {
+ for (const value of values) {
+ if (value) params.append(key, value);
+ }
+ };
+
+ add('q', [state.q?.trim().replace(/\s+/g, ' ')]);
+ add(
+ 'type',
+ sortedTypes(state.types).map((type) => WINE_TYPES[type].slug),
+ );
+ add('land', [...(state.countries ?? [])].sort());
+ add('drue', [...(state.grapes ?? [])].sort());
+ add('mat', [...(state.foods ?? [])].sort());
+ add('vurdering', [state.minRating?.toString()]);
+ add('alkohol', [state.alcohol && ALCOHOL_SLUGS[state.alcohol]]);
+ add('sort', [state.sort]);
return params;
}
-/** Bygger lenke til søkesiden. Tom tilstand gir `/sok` (bla i alt). */
+/** Builds a link to the search page. An empty state gives `/sok`, which browses everything. */
export function buildSearchUrl(state: SearchState = {}): string {
const query = toSearchParams(state).toString();
return query ? `${SEARCH_PATH}?${query}` : SEARCH_PATH;
}
+/** All distinct values of a parameter that are not empty. */
+function readList(params: URLSearchParams, key: string): string[] {
+ return [...new Set(params.getAll(key).map((value) => value.trim()))].filter(Boolean);
+}
+
+/** Values that do not make sense are ignored, since anyone can edit a URL. */
export function parseSearchParams(params: URLSearchParams): SearchState {
const state: SearchState = {};
+
const q = params.get('q')?.trim();
if (q) state.q = q;
- const type = wineTypeFromSlug(params.get('type'));
- if (type) state.type = type;
- const country = params.get('land')?.trim();
- if (country) state.country = country;
- const grape = params.get('drue')?.trim();
- if (grape) state.grape = grape;
- const food = params.get('mat')?.trim();
- if (food) state.food = food;
+
+ const types = readList(params, 'type').flatMap((slug) => wineTypeFromSlug(slug) ?? []);
+ if (types.length > 0) state.types = types;
+
+ const countries = readList(params, 'land');
+ if (countries.length > 0) state.countries = countries;
+
+ const grapes = readList(params, 'drue');
+ if (grapes.length > 0) state.grapes = grapes;
+
+ const foods = readList(params, 'mat');
+ if (foods.length > 0) state.foods = foods;
+
+ const minRating = Number(params.get('vurdering'));
+ if (RATING_OPTIONS.includes(minRating)) state.minRating = minRating;
+
+ const alcoholSlug = params.get('alkohol');
+ const alcohol = (Object.keys(ALCOHOL_SLUGS) as AlcoholLevel[]).find(
+ (level) => ALCOHOL_SLUGS[level] === alcoholSlug,
+ );
+ if (alcohol) state.alcohol = alcohol;
+
const sort = params.get('sort') as SortOption | null;
if (sort && SORT_OPTIONS.includes(sort)) state.sort = sort;
+
return state;
}
+
+export function toggleValue(values: T[] = [], value: T): T[] {
+ return values.includes(value) ? values.filter((item) => item !== value) : [...values, value];
+}
+
+/** The number of selected filters. The search text and the sorting are not filters. */
+export function activeFilterCount({
+ types = [],
+ countries = [],
+ grapes = [],
+ foods = [],
+ minRating,
+ alcohol,
+}: SearchState): number {
+ return (
+ types.length +
+ countries.length +
+ grapes.length +
+ foods.length +
+ (minRating ? 1 : 0) +
+ (alcohol ? 1 : 0)
+ );
+}
diff --git a/frontend/src/test/searchMocks.ts b/frontend/src/test/searchMocks.ts
index 98e0bd9..46f139b 100644
--- a/frontend/src/test/searchMocks.ts
+++ b/frontend/src/test/searchMocks.ts
@@ -1,6 +1,7 @@
import { vi } from 'vitest';
import type { MockLink } from '@apollo/client/testing';
import type { ApiWine } from '../lib/mapWine';
+import { FILTER_OPTIONS_QUERY } from '../features/search/api/filterOptionsQuery';
import { SEARCH_WINES_QUERY } from '../features/search/api/searchQuery';
/** Variables a test can read back to see what was sent to the API. */
@@ -17,6 +18,7 @@ const wine = (id: number): ApiWine & { __typename: string } => ({
type: 'Red',
grapes: ['Pinot Noir'],
country: 'France',
+ countryCode: 'FR',
wineryName: 'Produsent',
communityRating: 4,
communityRatingCount: 10,
@@ -59,3 +61,34 @@ export function searchMock(totalFor: (variables: SentVariables) => number, pageS
};
return { mock, resolver };
}
+
+const option = (value: string, count: number) => ({
+ __typename: 'FilterOption',
+ value,
+ label: value,
+ count,
+});
+
+/** A mock for the filter panel. The eight grapes are enough to need "Vis alle". */
+export function filterOptionsMock({ fails = false } = {}) {
+ const mock: MockLink.MockedResponse = {
+ request: { query: FILTER_OPTIONS_QUERY, variables: () => true },
+ maxUsageCount: Number.POSITIVE_INFINITY,
+ ...(fails
+ ? { error: new Error('Filtre nede') }
+ : {
+ result: {
+ data: {
+ filterOptions: {
+ __typename: 'FilterOptions',
+ types: [option('Red', 53), option('White', 19)],
+ countries: [option('IT', 25), option('FR', 19)],
+ grapes: Array.from({ length: 8 }, (_, i) => option(`Drue${i + 1}`, 9 - i)),
+ harmonize: [option('Beef', 53)],
+ },
+ },
+ },
+ }),
+ };
+ return { mock };
+}
From 5be374be2a1abebcd6ad6aaaf0f19a74ab34887d Mon Sep 17 00:00:00 2001
From: Oscar Bakkeng
Date: Sat, 7 Nov 2026 18:58:57 +0100
Subject: [PATCH 3/3] docs(readme): update status after adding filters and
sorting (#35)
Co-Authored-By: Claude Opus 5.5
---
README.md | 22 +++++++++++-----------
1 file changed, 11 insertions(+), 11 deletions(-)
diff --git a/README.md b/README.md
index 6f45fdf..b0b2c61 100644
--- a/README.md
+++ b/README.md
@@ -49,7 +49,7 @@ Submission 3 should be the first complete prototype, with search, browsing, sort
| 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 | 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 |
+| Filtering and sorting in the user interface | Done | Filter panel, active filters and sorting on `/sok`. Needs the new backend on the VM |
| Wine detail page | Done | Facts, food pairing and rating at `/vin/:id`. Student reviews are added with the reviews feature |
| Student reviews (stored in the database) | Planned | |
| Larger dataset on the VM | Planned | |
@@ -99,10 +99,10 @@ This section describes what users can do. "Backend" means the API supports the f
| Feature | Backend | UI | Description |
|---|---|---|---|
| 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 |
+| Filtering | Done | Done | Type, country, grapes, food pairing, minimum rating and alcohol range. Several values can be selected. The counts follow the search and the other filters. On small screens the filters open in a dialog |
+| Sorting | Done | Done | Top rated, most rated, name and alcohol. Always sorts the whole result, not only the loaded page |
| 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 |
+| Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&vurdering=&alkohol=&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)`) | Done | Name, winery, region, grapes, alcohol, body, acidity, vintages and food pairing in Norwegian. Grapes and food link to the search. Student reviews are planned |
| 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 |
@@ -137,6 +137,8 @@ Each row explains what we chose, why, and what else we considered. Added as the
| 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 |
+| Filter panel on small screens | Native `` with `showModal()` | The browser handles focus trapping, Escape and returning focus, with no extra JavaScript | A dialog library |
+| Filter counts | One count query per group that leaves out the group's own filter | The user can see what each choice gives before choosing, and values can be combined | Fixed counts for the whole catalogue |
| 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) |
@@ -198,10 +200,8 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing,
### Some known gaps
-- The filter panel is not built yet, so it is 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.
## Sustainability
@@ -229,7 +229,7 @@ We follow the principle from the course: measure, set a budget and show the numb
| Metric | Budget | Measured | Date | How we measure |
|---|---|---|---|---|
-| JavaScript on the landing page (gzip) | Less than 150 kB | 154,89 kB (over budget after adding Apollo Client) | 7 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 | 155,05 kB (over budget after adding Apollo Client) | 7 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 |
@@ -243,14 +243,14 @@ 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 | 188 |
+| 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 | 233 |
| 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 | Landing, search and detail pages with a stubbed API: one request per page load, debounce, search, load more, reload, back button, from search to wine and back, no hits, wine not found, API errors, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 40 (20 tests in 2 browser projects) |
+| End-to-end | Playwright with axe-core, desktop and mobile | Landing, search and detail pages with a stubbed API: one request per page load, debounce, search, filters, sorting, load more, reload, back button, from search to wine and back, the filter dialog on mobile, no hits, wine not found, API errors, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 50 (24 tests in 2 browser projects, and 2 for mobile only) |
| API | Not set up yet | Resolvers against a test database: search, filtering, sorting and pagination | Planned |
Counted on 7 November 2026.
-**Coverage (frontend, 7 November 2026):** lines 98.58 %, branches 82.39 %, functions 95.9 %, statements 89.18 %.
+**Coverage (frontend, 7 November 2026):** lines 98.93 %, branches 85.3 %, functions 97.14 %, statements 90.97 %.
Vitest enforces a minimum of 80 % for lines, functions and statements and 75 % for branches (`vitest.config.ts`).
We will add the missing tests before raising the limits further, and we do not lower the limits to make the run pass.
@@ -340,7 +340,7 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a
1. [x] Add Apollo Client to the frontend, with the endpoint `${import.meta.env.BASE_URL}graphql`.
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.
+3. [x] Filter panel with counts from `filterOptions`, and sorting. All choices stored in the URL.
4. [x] Connect the landing page to the backend.
5. [x] Wine detail page.
6. [ ] Start the backend on the VM and load the dataset.