Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ Submission 3 should be the first complete prototype, with search, browsing, sort
| Frontend deployed on the VM | Done | Deep links such as `/project2/sok` work on reload |
| Backend running on the VM | Done | Started with `nohup`, see [VM guide](docs/vm.md) |
| Apollo Client in the frontend | Done | |
| Search page with results | Next | Placeholder page at `/sok` |
| Filtering and sorting in the user interface | Planned | Already supported by the API |
| Search page with results | Done | Search with debounce, number of hits and "Last inn flere" at `/sok` |
| Filtering and sorting in the user interface | Next | The API and URL filters work, but the panel is missing |
| Wine detail page | Planned | Placeholder page at `/vin/:id` |
| Student reviews (stored in the database) | Planned | |
| Larger dataset on the VM | Planned | |
Expand Down Expand Up @@ -98,11 +98,11 @@ This section describes what users can do. "Backend" means the API supports the f

| Feature | Backend | UI | Description |
|---|---|---|---|
| Search | Done | Planned | Ignores case and accents. Matches name, winery, region and grapes |
| Search | Done | Done | Ignores case and accents. Matches name, winery, region and grapes as one phrase. Waits 300 ms after the last key press |
| Filtering | Done | Planned | Type, country, grapes, food pairing, minimum rating and alcohol range. Shows the number of wines for each option |
| Sorting | Done | Planned | Top rated, most rated, name and alcohol. Always sorts the whole result, not only the loaded page |
| Pagination | Done | Planned | Cursor-based. The user loads more results with a button, not with infinite scroll |
| Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&sort=`. Survives reloads and works with the back button |
| Pagination | Done | Done | Cursor-based. The user loads more results with a button, not with infinite scroll. Focus moves to the first new wine |
| Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&sort=`. Survives reloads. Typing replaces the history entry, so the back button leaves the search instead of stepping through every word |
| Wine detail page | Done (`wine(id)`) | Planned | Name, winery, region, grapes, alcohol, food pairing, both ratings, and the latest student reviews |
| Student reviews | Planned | Planned | Die roll from 1 to 6 and an optional comment, stored in PostgreSQL, the new rating is shown at once without a reload (Apollo cache update) |
| Wishlist ("Vil prøve") | Planned | Done, stored in the browser | Moves to the backend when users and reviews are in place |
Expand Down Expand Up @@ -134,8 +134,9 @@ Each row explains what we chose, why, and what else we considered. Added as the
| Styling | CSS Modules and design tokens in `styles/tokens.css` | No runtime cost and no extra dependency. Tokens make dark mode and consistent colours easy | Tailwind, styled-components |
| API | GraphQL with Apollo Server on Express | Required by the course. The client asks only for the fields it shows, which saves data | REST |
| Database | PostgreSQL with the `pg_trgm` extension | Fast text search with `ILIKE` also on many rows. Already available on the VM | MongoDB, SQLite |
| Pagination | Cursor-based | Stable when sorting. No duplicates or gaps when new data is added | Offset-based |
| Pagination | Cursor-based, pages merged in the Apollo cache | Stable when sorting. No duplicates or gaps when new data is added | Offset-based |
| Search, filtering and sorting | In the database | Scales to large datasets. The frontend never loads the whole catalogue | Filtering in the browser |
| Search state flow | Field text in React state, debounced into the URL, and the query reads only the URL | One source of truth for the search, so reload, shared links and the back button all give the same result | Sending a request directly from the input |
| Testing | Vitest, React Testing Library, Playwright, axe | Vitest shares configuration with Vite. Playwright tests real browsers, also on mobile | Jest, Cypress |
| Deployment | Apache serves static files, the backend runs with `nohup` | Matches the course VM | systemd service (possible improvement) |

Expand Down Expand Up @@ -197,7 +198,7 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing,

### Some known gaps

- The search page, filters and detail page are not built yet, so they are not tested.
- The filter panel and detail page are not built yet, so they are not tested.
- We have not tested with a screen reader yet.
- eslint-plugin-jsx-a11y is not set up yet.
- The filter panel on mobile will need a dialog with correct focus handling. This is planned.
Expand All @@ -219,16 +220,16 @@ We follow the principle from the course: measure, set a budget and show the numb
- The landing page loads all its data in one GraphQL query, with only the fields it shows. An end-to-end test checks that only one request is sent.
- Search, filtering, sorting and pagination run in the database. A page returns at most 50 wines.
- The Apollo cache, so we do not fetch the same data twice.
- Debounce on the search field (300 ms). An end-to-end test checks that a whole word sends only one search.

**Planned:**
- Debounce on the search field (about 300 ms), so we do not send a request for every key press.
- Compression (gzip or Brotli) and cache headers in Apache.

### Budget and measurements

| Metric | Budget | Measured | Date | How we measure |
|---|---|---|---|---|
| JavaScript on the landing page (gzip) | Less than 150 kB | 152,82 kB (over budget after adding Apollo Client) | 6 Nov 2026 | Sum of the gzip sizes from `npm run build` for the files the landing page loads |
| JavaScript on the landing page (gzip) | Less than 150 kB | 154,01 kB (over budget after adding Apollo Client) | 6 Nov 2026 | Sum of the gzip sizes from `npm run build` for the files the landing page loads |
| Data transferred when loading the landing page | Less than 300 kB | Not measured yet | | Chrome DevTools, Network tab, cache disabled, on the VM |
| Data transferred in a fixed search scenario | Less than 500 kB | Not measured yet | | Same method. Needs the search page |
| Lighthouse (mobile) | Performance at least 90, accessibility 100 | Performance 39, accessibility 100, best practices 100, SEO 100 | 30 Oct 2026 | Lighthouse in Chrome DevTools, incognito, against the VM |
Expand All @@ -242,18 +243,16 @@ and because the test was run over VPN. These are the "before" numbers. We will m

| Level | Tools | What we test | Number of tests |
|---|---|---|---|
| Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, mapping of API data, data hooks, components, the landing page, loading, empty and error states, and axe on each component | 70 |
| Unit and components (frontend) | Vitest, React Testing Library, user-event, vitest-axe | URL parameters, formatting, mapping of API data, data hooks, components, the landing page, loading, empty and error states, and axe on each component | 134 |
| Unit (backend) | Vitest | Parsing of X-Wines CSV files, and building SQL for search, filtering and sorting | 2 test files |
| End-to-end | Playwright with axe-core, desktop and mobile | One GraphQL request for the landing page (stubbed API), search from the landing page, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 12 (6 tests in 2 browser projects) |
| End-to-end | Playwright with axe-core, desktop and mobile | Landing page and search page with a stubbed API: one request per page load, debounce, search, load more, reload, back button, no hits, API errors, keyboard use, reflow at 320 px, and no axe violations (WCAG 2.1 AA) | 26 (13 tests in 2 browser projects) |
| API | Not set up yet | Resolvers against a test database: search, filtering, sorting and pagination | Planned |

Counted on 6 November 2026.

**Coverage (frontend, 6 November 2026):** lines 84.26 %, branches 60.69 %, functions 83.33 %, statements 70.19 %.
**Coverage (frontend, 6 November 2026):** lines 98.32 %, branches 79.6 %, functions 95 %, statements 87.71 %.

Vitest enforces a minimum of 80 % for lines, functions and statements and 75 % for branches (`vitest.config.ts`).
The coverage run currently fails these limits. The main reasons are hooks without their own tests
(for example `useWishlist`) and placeholder pages for search and wine details that will be replaced.
We will add the missing tests before raising the limits further, and we do not lower the limits to make the run pass.

We leave out `main.tsx`, test files, test helpers and mock data, because they contain no application logic.
Expand Down Expand Up @@ -340,7 +339,7 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a
### Next: complete the beta

1. [x] Add Apollo Client to the frontend, with the endpoint `${import.meta.env.BASE_URL}graphql`.
2. [ ] Search page: search field with debounce, list of results, number of hits, "Last inn flere", and empty and error states.
2. [x] Search page: search field with debounce, list of results, number of hits, "Last inn flere", and empty and error states.
3. [ ] Filter panel with counts from `filterOptions`, and sorting. All choices stored in the URL.
4. [x] Connect the landing page to the backend.
5. [ ] Wine detail page.
Expand All @@ -358,7 +357,8 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a
### Some known issues

- Some documents in `docs/` still describe the old Vinmonopolet plan and the old test endpoint `/api/hello`. They will be updated.
- Frontend test coverage is below our enforced limits (statements 70.19 %, branches 60.69 %). Tests for `useWishlist` and the remaining components are planned.
- Search matches the text as one phrase, so "noir pinot" finds nothing. Country is not part of the search text, because the country filter covers it.
- The cursors in the API hold an offset, which is slower deep into large results. To be solved together with the larger dataset.

<!--
Remove known issues as they are fixed.
Expand Down
166 changes: 166 additions & 0 deletions frontend/e2e/search.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';

/*
* E2E for the search page. Runs against `vite preview` with a stubbed GraphQL API that
* behaves like the real one: 30 wines match "pinot", nothing matches "finnesikke".
*/
interface Variables {
search?: string;
after?: string;
first?: number;
}

const wine = (id: number) => ({
__typename: 'Wine',
id: String(id),
name: `Pinot ${id}`,
type: 'Red',
grapes: ['Pinot Noir'],
country: 'France',
wineryName: 'Testprodusent',
communityRating: 4.5,
communityRatingCount: 10,
});

function winesResponse({ search, after, first = 24 }: Variables) {
const total = search === 'finnesikke' ? 0 : 30;
const start = Number(after ?? 0);
const end = Math.min(start + first, total);
const ids = Array.from({ length: Math.max(end - start, 0) }, (_, i) => start + i + 1);
return {
data: {
wines: {
__typename: 'WineConnection',
totalCount: total,
edges: ids.map((id) => ({
__typename: 'WineEdge',
cursor: String(id),
node: wine(id),
})),
pageInfo: {
__typename: 'PageInfo',
hasNextPage: end < total,
endCursor: ids.length ? String(end) : null,
},
},
},
};
}

async function stubApi(page: Page) {
const searches: Variables[] = [];
await page.route('**/project2/graphql', (route) => {
const { operationName, variables } = route.request().postDataJSON() as {
operationName: string;
variables: Variables;
};
if (operationName !== 'SearchWines') return route.abort();
searches.push(variables);
return route.fulfill({ json: winesResponse(variables) });
});
return searches;
}

const searchbox = (page: Page) => page.getByRole('searchbox', { name: 'Søk etter vin' });
const results = (page: Page) => page.getByRole('list', { name: 'Søkeresultater' });

test.describe('Søkesiden', () => {
test('søk, last inn flere, last siden på nytt og gå tilbake', async ({ page }) => {
await stubApi(page);
await page.goto('./sok');
await expect(results(page).getByRole('article')).toHaveCount(24);

await searchbox(page).pressSequentially('pinot', { delay: 30 });
await expect(page).toHaveURL(/\/sok\?q=pinot$/);
await expect(page.getByRole('status')).toHaveText('Viser 24 av 30 viner for «pinot»');

await page.getByRole('button', { name: 'Last inn flere' }).click();
await expect(results(page).getByRole('article')).toHaveCount(30);
await expect(page.getByRole('link', { name: 'Pinot 25' })).toBeFocused();
await expect(page.getByRole('button', { name: 'Last inn flere' })).toHaveCount(0);

await page.reload();
await expect(searchbox(page)).toHaveValue('pinot');
await expect(page.getByRole('status')).toHaveText('Viser 24 av 30 viner for «pinot»');

await page.getByRole('link', { name: 'Pinot 1', exact: true }).click();
await expect(page).toHaveURL(/\/vin\/1$/);
await page.goBack();
await expect(searchbox(page)).toHaveValue('pinot');
});

test('sender bare ett søk når brukeren skriver et helt ord', async ({ page }) => {
const searches = await stubApi(page);
await page.goto('./sok');
await expect(results(page).getByRole('article')).toHaveCount(24);

await searchbox(page).pressSequentially('riesling', { delay: 30 });
await expect(page).toHaveURL(/\/sok\?q=riesling$/);
await expect(page.getByRole('status')).toContainText('riesling');

expect(searches.map((variables) => variables.search)).toEqual([undefined, 'riesling']);
});

test('forklarer når søket ikke gir treff, og kan gå tilbake til alle viner', async ({ page }) => {
await stubApi(page);
await page.goto('./sok?q=finnesikke');
await expect(page.getByText('Ingen viner passer til «finnesikke».')).toBeVisible();

await page.getByRole('link', { name: 'Se alle viner' }).click();

await expect(searchbox(page)).toHaveValue('');
await expect(results(page).getByRole('article')).toHaveCount(24);
});

test('viser feil og kan prøve igjen når API-et er nede', async ({ page }) => {
let down = true;
await page.route('**/project2/graphql', (route) => {
if (down) return route.fulfill({ status: 503, body: 'Service Unavailable' });
return route.fulfill({ json: winesResponse({}) });
});
await page.goto('./sok');
await expect(page.getByRole('alert')).toContainText('Vi fikk ikke søkt');

down = false;
await page.getByRole('button', { name: 'Prøv igjen' }).click();

await expect(results(page).getByRole('article')).toHaveCount(24);
});

test('kan brukes med bare tastatur', async ({ page }) => {
await stubApi(page);
await page.goto('./sok');
await expect(results(page).getByRole('article')).toHaveCount(24);

await searchbox(page).focus();
await page.keyboard.type('pinot');
await page.keyboard.press('Enter');

await expect(page).toHaveURL(/\/sok\?q=pinot$/);
await expect(searchbox(page)).toBeFocused();
});

test('har ingen axe-brudd (WCAG 2.1 AA)', async ({ page }) => {
await stubApi(page);
await page.goto('./sok?q=pinot');
await expect(results(page).getByRole('article')).toHaveCount(24);
const axe = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
.analyze();
expect(axe.violations).toEqual([]);
});

test('har ingen horisontal scroll ved 320 px, heller ikke med et langt søkeord', async ({
page,
}) => {
await stubApi(page);
await page.setViewportSize({ width: 320, height: 640 });
await page.goto(`./sok?q=${'a'.repeat(200)}`);
await expect(results(page).getByRole('article')).toHaveCount(24);
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(overflow).toBe(false);
});
});
38 changes: 38 additions & 0 deletions frontend/src/app/App.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { Suspense } from 'react';
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing/react';
import { MemoryRouter } from 'react-router';
import { createApolloCache } from '../lib/apollo';
import { searchMock } from '../test/searchMocks';
import { AppRoutes } from './App';

function renderRoute(route: string) {
render(
<MockedProvider mocks={[searchMock(() => 1).mock]} cache={createApolloCache()}>
<MemoryRouter initialEntries={[route]}>
<Suspense fallback={null}>
<AppRoutes />
</Suspense>
</MemoryRouter>
</MockedProvider>,
);
}

describe('AppRoutes', () => {
it.each([
['/finnes-ikke', 'Fant ikke siden'],
['/vin/1', 'Vin'],
['/mine', 'Mine anmeldelser'],
])('shows the right page for %s', async (route, heading) => {
renderRoute(route);
expect(await screen.findByRole('heading', { level: 1, name: heading })).toBeInTheDocument();
});

it('loads the search page lazily', async () => {
renderRoute('/sok');
expect(
await screen.findByRole('heading', { level: 1, name: 'Utforsk viner' }),
).toBeInTheDocument();
});
});
11 changes: 7 additions & 4 deletions frontend/src/components/layout/AppLayout.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ function renderApp(route = '/') {
<Route element={<AppLayout />}>
<Route index element={<h1>Forside</h1>} />
<Route path="sok" element={<h1>Søk</h1>} />
<Route path="mine" element={<h1>Mine</h1>} />
</Route>
</Routes>
</MemoryRouter>,
Expand All @@ -37,11 +38,13 @@ describe('AppLayout', () => {
expect(screen.getByRole('contentinfo')).toHaveTextContent('Drikk med måte');
});

it('skjuler headersøket på forsiden, men viser det ellers', () => {
const { unmount } = renderApp('/');
it.each(['/', '/sok'])('skjuler headersøket på %s, som har sitt eget søkefelt', (route) => {
renderApp(route);
expect(screen.queryByRole('search', { name: 'Søk i toppmenyen' })).not.toBeInTheDocument();
unmount();
renderApp('/sok');
});

it('viser headersøket på andre sider', () => {
renderApp('/mine');
expect(screen.getByRole('search', { name: 'Søk i toppmenyen' })).toBeInTheDocument();
});

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/layout/AppLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function AppLayout() {
<a href="#main" className={styles.skipLink}>
Hopp til hovedinnhold
</a>
<Header showSearch={pathname !== '/'} />
<Header showSearch={pathname !== '/' && pathname !== '/sok'} />
<main id="main" ref={mainRef} tabIndex={-1} className={styles.main}>
<Suspense
fallback={
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/layout/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { LogoMark } from './Logo';
import styles from './Header.module.css';

interface HeaderProps {
/** Forsiden har et stort søkefelt i hero, så headersøket skjules der. */
/** Forsiden og søkesiden har egne store søkefelt, så headersøket skjules der. */
showSearch?: boolean;
}

Expand Down
18 changes: 18 additions & 0 deletions frontend/src/components/ui/ErrorNotice.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
.notice {
display: grid;
justify-items: start;
gap: var(--space-3);
padding-block: var(--space-5);
border-left: 4px solid var(--color-danger);
}

.retry {
min-height: var(--tap-target);
padding: 0 var(--space-5);
border: 0;
border-radius: var(--radius-pill);
background: var(--color-brand);
color: var(--color-on-brand);
font-weight: 700;
cursor: pointer;
}
21 changes: 21 additions & 0 deletions frontend/src/components/ui/ErrorNotice.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import styles from './ErrorNotice.module.css';

interface ErrorNoticeProps {
message: string;
onRetry?: () => void;
className?: string;
}

/** Error message that is announced at once, with a way to try again. */
export function ErrorNotice({ message, onRetry, className = '' }: ErrorNoticeProps) {
return (
<div className={`${className} ${styles.notice}`} role="alert">
<p>{message}</p>
{onRetry && (
<button type="button" className={styles.retry} onClick={onRetry}>
Prøv igjen
</button>
)}
</div>
);
}
Loading