From 4826f1248b082e90fd00a6501bcee7377bd9d43e Mon Sep 17 00:00:00 2001
From: Oscar Bakkeng
Date: Thu, 26 Nov 2026 19:02:54 +0100
Subject: [PATCH 1/2] feat(landing): add search suggestions to the landing page
(#30)
---
README.md | 9 +-
backend/src/wine-query.test.ts | 18 +-
backend/src/wine-query.ts | 16 +-
docs/api.md | 3 +-
frontend/e2e/landing.spec.ts | 2 +-
frontend/e2e/suggestions.spec.ts | 131 +++++++++++
frontend/package-lock.json | 69 +++++-
frontend/package.json | 1 +
.../src/features/landing/LandingView.test.tsx | 4 +-
.../features/landing/api/suggestionsQuery.ts | 20 ++
.../landing/api/useWineSuggestions.ts | 74 ++++++
.../landing/components/Hero.module.css | 4 +-
.../src/features/landing/components/Hero.tsx | 8 +-
.../landing/components/HeroSearch.module.css | 59 +++++
.../landing/components/HeroSearch.test.tsx | 213 ++++++++++++++++++
.../landing/components/HeroSearch.tsx | 138 ++++++++++++
frontend/src/hooks/useDebouncedValue.ts | 13 ++
frontend/src/test/listRoles.test.ts | 3 +-
18 files changed, 765 insertions(+), 20 deletions(-)
create mode 100644 frontend/e2e/suggestions.spec.ts
create mode 100644 frontend/src/features/landing/api/suggestionsQuery.ts
create mode 100644 frontend/src/features/landing/api/useWineSuggestions.ts
create mode 100644 frontend/src/features/landing/components/HeroSearch.module.css
create mode 100644 frontend/src/features/landing/components/HeroSearch.test.tsx
create mode 100644 frontend/src/features/landing/components/HeroSearch.tsx
create mode 100644 frontend/src/hooks/useDebouncedValue.ts
diff --git a/README.md b/README.md
index 20259ae..a0974a3 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# Kork & Krone
-**Last updated:** 23 November 2026
+**Last updated:** 24 November 2026
**Submission:** 4 (working system, ready for feedback on every aspect)
**Status:** In progress. See [Status for submission 4](#status-for-submission-4).
@@ -123,7 +123,8 @@ 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 |
+| Search | Done | Done | Ignores case and accents. Matches name, winery, region and grapes, with the words in any order, so «noir pinot» finds Pinot Noir. Waits 300 ms after the last key press |
+| Search suggestions | Done | Done | On the landing page only: up to 5 wines while the user types, with arrow keys, Enter and Escape. The last choice opens all results on `/sok`. Enter without a chosen suggestion is a normal search |
| 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 | Pages behind an opaque cursor that holds an offset. The user loads more results with a button, not with infinite scroll. Focus moves to the first new wine |
@@ -171,6 +172,7 @@ Each row explains what we chose, why, and what else we considered. Added as the
| Expired session | An Apollo link that fetches `me` again when the API says `UNAUTHENTICATED` | The whole page shows at once that the user is logged out, wherever the error came from | Checking for the error in each feature |
| Batched lookups | DataLoader for reviews and ratings per wine | A page of wines runs one query per field instead of one per wine (the N+1 problem) | One query per wine |
| Search state flow | Field text in React state, debounced into the URL, and the query reads only the URL | One source of truth for the search, so reload, shared links and the back button all give the same result | Sending a request directly from the input |
+| Search suggestions | Downshift (`useCombobox`) | A tested implementation of the WAI-ARIA combobox pattern with no styling of its own, so it fits our design. Building our own risks subtle errors with keyboard and screen readers. It adds about 13 kB (gzip) to the landing page | Our own combobox, React Aria, Headless UI |
| Filter panel on small screens | Native `
-
+
diff --git a/frontend/src/features/landing/components/HeroSearch.module.css b/frontend/src/features/landing/components/HeroSearch.module.css
new file mode 100644
index 0000000..d661f3e
--- /dev/null
+++ b/frontend/src/features/landing/components/HeroSearch.module.css
@@ -0,0 +1,59 @@
+/* The suggestions float over the content below, so the page does not jump while typing. */
+.combobox {
+ position: relative;
+}
+
+.menu {
+ display: none;
+ position: absolute;
+ z-index: 10;
+ top: 100%;
+ left: 0;
+ right: 0;
+ margin: var(--space-2) 0 0;
+ padding: var(--space-1);
+ list-style: none;
+ background: var(--color-surface);
+ color: var(--color-text);
+ border: 1px solid var(--color-border);
+ border-radius: var(--radius-md);
+ box-shadow: var(--shadow-md);
+}
+
+.open {
+ display: block;
+}
+
+.item {
+ display: grid;
+ gap: 2px;
+ min-height: var(--tap-target);
+ padding: var(--space-2) var(--space-3);
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+}
+
+/* The highlighted suggestion is also what the arrow keys and Enter act on. */
+.highlighted {
+ background: var(--color-surface-muted);
+ outline: 2px solid var(--color-focus);
+ outline-offset: -2px;
+}
+
+.name {
+ font-weight: 700;
+ overflow-wrap: anywhere;
+}
+
+.details {
+ font-size: var(--text-sm);
+ color: var(--color-text-muted);
+ overflow-wrap: anywhere;
+}
+
+.all {
+ align-self: center;
+ color: var(--color-link);
+ text-decoration: underline;
+ overflow-wrap: anywhere;
+}
diff --git a/frontend/src/features/landing/components/HeroSearch.test.tsx b/frontend/src/features/landing/components/HeroSearch.test.tsx
new file mode 100644
index 0000000..255af82
--- /dev/null
+++ b/frontend/src/features/landing/components/HeroSearch.test.tsx
@@ -0,0 +1,213 @@
+import { describe, expect, it, vi } from 'vitest';
+import { screen, waitFor, within } from '@testing-library/react';
+import type { MockLink } from '@apollo/client/testing';
+import { axe } from 'vitest-axe';
+import { renderWithRouter } from '../../../test/render';
+import { SUGGESTIONS_QUERY } from '../api/suggestionsQuery';
+import { HeroSearch } from './HeroSearch';
+
+interface Variables {
+ search: string;
+ first: number;
+}
+
+const wine = (id: number, name: string) => ({
+ __typename: 'Wine',
+ id: String(id),
+ name,
+ type: 'Red',
+ wineryName: 'Produsent',
+ country: 'France',
+ countryCode: 'FR',
+});
+
+const WINES = [wine(1, 'Pinot Noir Reserve'), wine(2, 'Haven Pinot Noir'), wine(3, 'Pinot Grigio')];
+
+/** Answers every suggestion request. «finnesikke» gives no wines. */
+function suggestionsMock({ fails = false } = {}) {
+ const resolver = vi.fn((variables: Variables) => {
+ const wines = variables.search === 'finnesikke' ? [] : WINES.slice(0, variables.first);
+ return {
+ data: {
+ wines: {
+ __typename: 'WineConnection',
+ totalCount: wines.length === 0 ? 0 : 42,
+ edges: wines.map((node) => ({ __typename: 'WineEdge', node })),
+ },
+ },
+ };
+ });
+ const mock: MockLink.MockedResponse = {
+ request: { query: SUGGESTIONS_QUERY, variables: () => true },
+ maxUsageCount: Number.POSITIVE_INFINITY,
+ ...(fails
+ ? { error: new Error('Nede') }
+ : { result: (variables) => resolver(variables as Variables) }),
+ };
+ return { mock, resolver };
+}
+
+function renderSearch(mocks: MockLink.MockedResponse[] = [suggestionsMock().mock]) {
+ return renderWithRouter(
, { mocks });
+}
+
+const combobox = () => screen.getByRole('combobox', { name: 'Hva har du lyst til å smake?' });
+const location = () => screen.getByTestId('location');
+
+describe('HeroSearch – forslag', () => {
+ it('spør ikke API-et før brukeren har skrevet to tegn', async () => {
+ const { mock, resolver } = suggestionsMock();
+ const { user } = renderSearch([mock]);
+
+ await user.type(combobox(), 'p');
+ await new Promise((resolve) => setTimeout(resolve, 400));
+
+ expect(resolver).not.toHaveBeenCalled();
+ expect(screen.queryAllByRole('option')).toHaveLength(0);
+ });
+
+ it('henter fem forslag én gang etter at brukeren har skrevet ferdig', async () => {
+ const { mock, resolver } = suggestionsMock();
+ const { user } = renderSearch([mock]);
+
+ await user.type(combobox(), 'pinot');
+
+ expect(await screen.findByRole('option', { name: /Pinot Noir Reserve/ })).toBeInTheDocument();
+ expect(resolver).toHaveBeenCalledOnce();
+ expect(resolver).toHaveBeenCalledWith(expect.objectContaining({ search: 'pinot', first: 5 }));
+ expect(combobox()).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('sender ordene slik brukeren skrev dem, så «noir pinot» også gir treff', async () => {
+ const { mock, resolver } = suggestionsMock();
+ const { user } = renderSearch([mock]);
+
+ await user.type(combobox(), 'noir pinot');
+
+ await screen.findByRole('option', { name: /Haven Pinot Noir/ });
+ expect(resolver).toHaveBeenLastCalledWith(expect.objectContaining({ search: 'noir pinot' }));
+ });
+
+ it('viser type, land og produsent på norsk under navnet', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'pinot');
+
+ const option = await screen.findByRole('option', { name: /Pinot Grigio/ });
+ expect(option).toHaveTextContent('Rødvin · Frankrike · Produsent');
+ });
+
+ it('forteller skjermlesere hvor mange forslag det er', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'pinot');
+
+ await screen.findByRole('option', { name: /Pinot Grigio/ });
+ expect(screen.getByTestId('suggestions-status')).toHaveTextContent(
+ '3 forslag. Bruk piltastene for å velge.',
+ );
+ });
+
+ it('har «Se alle treff» som siste valg, med antall', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'pinot');
+
+ await screen.findByRole('option', { name: /Pinot Grigio/ });
+ expect(screen.getAllByRole('option').at(-1)).toHaveTextContent('Se alle 42 treff for «pinot»');
+ });
+});
+
+describe('HeroSearch – valg', () => {
+ it('går til vinen med piltaster og Enter', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'pinot');
+ await screen.findByRole('option', { name: /Pinot Grigio/ });
+
+ await user.keyboard('{ArrowDown}{ArrowDown}{Enter}');
+
+ expect(location()).toHaveTextContent('/vin/2');
+ });
+
+ it('går til vinen ved klikk', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'pinot');
+
+ await user.click(await screen.findByRole('option', { name: /Pinot Grigio/ }));
+
+ expect(location()).toHaveTextContent('/vin/3');
+ });
+
+ it('åpner alle treff på søkesiden fra det siste valget', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'pinot');
+
+ await user.click(await screen.findByRole('option', { name: /Se alle 42 treff/ }));
+
+ expect(location()).toHaveTextContent('/sok?q=pinot');
+ });
+
+ it('søker som før med Enter når ingen forslag er valgt', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'pinot noir');
+ await screen.findByRole('option', { name: /Pinot Grigio/ });
+
+ await user.keyboard('{Enter}');
+
+ expect(location()).toHaveTextContent('/sok?q=pinot+noir');
+ });
+
+ it('søker også med knappen', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'barolo');
+
+ await user.click(screen.getByRole('button', { name: 'Søk' }));
+
+ expect(location()).toHaveTextContent('/sok?q=barolo');
+ });
+
+ it('lukker forslagene med Escape og beholder teksten', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'pinot');
+ await screen.findByRole('option', { name: /Pinot Grigio/ });
+
+ await user.keyboard('{Escape}');
+
+ expect(combobox()).toHaveAttribute('aria-expanded', 'false');
+ expect(screen.queryAllByRole('option')).toHaveLength(0);
+ expect(combobox()).toHaveValue('pinot');
+ });
+});
+
+describe('HeroSearch – tilstander', () => {
+ it('viser bare «Se alle treff» når ingen viner passer', async () => {
+ const { user } = renderSearch();
+ await user.type(combobox(), 'finnesikke');
+
+ await waitFor(() =>
+ expect(screen.getByTestId('suggestions-status')).toHaveTextContent('Ingen forslag.'),
+ );
+ const options = screen.getAllByRole('option');
+ expect(options).toHaveLength(1);
+ expect(options[0]).toHaveTextContent('Søk etter «finnesikke»');
+ });
+
+ it('stopper ikke søket når forslagene feiler', async () => {
+ const { user } = renderSearch([suggestionsMock({ fails: true }).mock]);
+ await user.type(combobox(), 'pinot');
+ await new Promise((resolve) => setTimeout(resolve, 400));
+
+ const options = await screen.findAllByRole('option');
+ expect(options).toHaveLength(1);
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+
+ await user.keyboard('{Enter}');
+ expect(location()).toHaveTextContent('/sok?q=pinot');
+ });
+
+ it('har ingen axe-brudd med åpne forslag', async () => {
+ const { user, container } = renderSearch();
+ await user.type(combobox(), 'pinot');
+ const listbox = await screen.findByRole('listbox');
+ await within(listbox).findAllByRole('option');
+
+ expect(await axe(container)).toHaveNoViolations();
+ });
+});
diff --git a/frontend/src/features/landing/components/HeroSearch.tsx b/frontend/src/features/landing/components/HeroSearch.tsx
new file mode 100644
index 0000000..8c312d7
--- /dev/null
+++ b/frontend/src/features/landing/components/HeroSearch.tsx
@@ -0,0 +1,138 @@
+import { useState, type FormEvent } from 'react';
+import { useCombobox } from 'downshift';
+import { useNavigate } from 'react-router';
+import formStyles from '../../../components/ui/SearchForm.module.css';
+import { formatCount } from '../../../lib/format';
+import { buildSearchUrl } from '../../../lib/searchParams';
+import { WINE_TYPES } from '../../../lib/wineTypes';
+import { useWineSuggestions, type WineSuggestion } from '../api/useWineSuggestions';
+import styles from './HeroSearch.module.css';
+
+type Suggestion = { kind: 'wine'; wine: WineSuggestion } | { kind: 'all'; query: string };
+
+const LABEL = 'Hva har du lyst til å smake?';
+
+/**
+ * The big search field on the landing page, with suggestions while the user types.
+ * Downshift gives the WAI-ARIA combobox pattern: arrow keys, Enter, Escape and the
+ * right roles. Enter without a highlighted suggestion is a normal search, so the
+ * suggestions never stand in the way.
+ */
+export function HeroSearch() {
+ const navigate = useNavigate();
+ const [text, setText] = useState('');
+ const { term, wines, totalCount, loading, error } = useWineSuggestions(text);
+
+ // «Se alle treff» is always last. If the suggestions fail, it is the only choice.
+ const items: Suggestion[] = term
+ ? [...wines.map((wine) => ({ kind: 'wine' as const, wine })), { kind: 'all', query: term }]
+ : [];
+
+ const { isOpen, highlightedIndex, getLabelProps, getInputProps, getMenuProps, getItemProps } =
+ useCombobox
({
+ items,
+ inputValue: text,
+ // Each choice leaves the page, so nothing is ever kept as selected.
+ selectedItem: null,
+ itemToString: (item) => (item?.kind === 'wine' ? item.wine.name : (item?.query ?? '')),
+ onInputValueChange: ({ inputValue }) => setText(inputValue ?? ''),
+ onSelectedItemChange: ({ selectedItem }) => {
+ if (selectedItem?.kind === 'wine') {
+ navigate(`/vin/${selectedItem.wine.id}`, { state: { from: '/' } });
+ } else if (selectedItem) {
+ navigate(buildSearchUrl({ q: selectedItem.query }));
+ }
+ },
+ // We announce the suggestions in our own live region below.
+ getA11yStatusMessage: () => '',
+ });
+
+ function handleSubmit(event: FormEvent) {
+ event.preventDefault();
+ navigate(buildSearchUrl({ q: text }));
+ }
+
+ const open = isOpen && items.length > 0;
+ const status = !open || loading ? '' : statusText(wines.length, Boolean(error));
+
+ return (
+
+ );
+}
+
+function statusText(count: number, failed: boolean): string {
+ if (count > 0) return `${count} forslag. Bruk piltastene for å velge.`;
+ return failed ? 'Forslag er ikke tilgjengelige. Trykk Enter for å søke.' : 'Ingen forslag.';
+}
+
+function allLabel(query: string, shown: number, totalCount: number | undefined): string {
+ if (shown === 0 || totalCount === undefined) return `Søk etter «${query}»`;
+ return `Se alle ${formatCount(totalCount)} treff for «${query}»`;
+}
diff --git a/frontend/src/hooks/useDebouncedValue.ts b/frontend/src/hooks/useDebouncedValue.ts
new file mode 100644
index 0000000..9fe9786
--- /dev/null
+++ b/frontend/src/hooks/useDebouncedValue.ts
@@ -0,0 +1,13 @@
+import { useEffect, useState } from 'react';
+
+/** The value, but only after it has stayed the same for `delayMs`. Saves a request per key press. */
+export function useDebouncedValue(value: T, delayMs: number): T {
+ const [debounced, setDebounced] = useState(value);
+
+ useEffect(() => {
+ const timer = setTimeout(() => setDebounced(value), delayMs);
+ return () => clearTimeout(timer);
+ }, [value, delayMs]);
+
+ return debounced;
+}
diff --git a/frontend/src/test/listRoles.test.ts b/frontend/src/test/listRoles.test.ts
index 8ff5cd3..8644492 100644
--- a/frontend/src/test/listRoles.test.ts
+++ b/frontend/src/test/listRoles.test.ts
@@ -20,7 +20,8 @@ describe('lister', () => {
.filter(([file]) => !INSIDE_NAV.includes(file))
.flatMap(([file, source]) =>
[...source.matchAll(/<(ul|ol)\b[^>]*>/g)]
- .filter(([tag]) => !tag.includes('role="list"'))
+ // Downshift's getMenuProps gives role="listbox", the right role for suggestions.
+ .filter(([tag]) => !tag.includes('role="list"') && !tag.includes('getMenuProps('))
.map(([tag]) => `${file}: ${tag}`),
);
expect(Object.keys(sources).length).toBeGreaterThan(20);
From d5c3b64f7d2605d37772ae94372e5e914cc4b1bc Mon Sep 17 00:00:00 2001
From: Oscar Bakkeng
Date: Thu, 26 Nov 2026 19:19:51 +0100
Subject: [PATCH 2/2] style(frontend): add the missing newline at the end of
README.md
---
frontend/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/frontend/README.md b/frontend/README.md
index 9057c79..f2da46f 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -15,4 +15,4 @@ Open the local URL printed by Vite. Vite forwards `/project2/graphql` to the bac
To build and publish on the VM, run `./scripts/deploy.sh` from the repository root on the VM.
It builds for `/project2/` and uses `sudo` to copy the output into `/var/www/html/project2`.
-See the [VM guide](../docs/vm.md).
\ No newline at end of file
+See the [VM guide](../docs/vm.md).