diff --git a/README.md b/README.md index c15e222..46b1cc4 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # Kork & Krone +**Last updated:** 24 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 +124,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. Every word must match, in any order. 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. «Best vurdert» puts wines with at least 50 ratings first, so a 5.0 from five people does not top the list | | 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 | @@ -172,6 +174,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 `` 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 | @@ -462,6 +465,7 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a ### Some known issues - Country is not part of the search text, because the country filter covers it. +- The search suggestions add about 13 kB (gzip) of JavaScript to the landing page, which is already over budget. Not measured on the VM yet. - The cursors in the API hold an offset, which is slower deep into large results. To be solved together with the larger dataset. - The database and its user are still called `vinmonopolet` and `vinmonopolet_app`, from before we switched dataset. Renaming would mean everyone rebuilding their database, so we kept the names. - Reviews from before login have no account and are shown as «Anonym student». The old `student` table they belong to will be removed later. diff --git a/docs/api.md b/docs/api.md index 8bea25f..4708921 100644 --- a/docs/api.md +++ b/docs/api.md @@ -35,7 +35,8 @@ https://doi.org/10.3390/bdcc7010020 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. +Search is case and accent insensitive and matches name, winery, region and grapes. Each word must +be found, in any order, so «noir pinot» finds «Pinot Noir». Up to 10 words are used. Several values in one filter list mean OR. Search and different filters are combined with AND. ```graphql 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). diff --git a/frontend/e2e/landing.spec.ts b/frontend/e2e/landing.spec.ts index 867e6ad..c3590de 100644 --- a/frontend/e2e/landing.spec.ts +++ b/frontend/e2e/landing.spec.ts @@ -70,7 +70,7 @@ test.describe('Forsiden', () => { }); test('søk fra forsiden lander på søkesiden med søkeordet i URL-en', async ({ page }) => { - await page.getByRole('searchbox', { name: 'Hva har du lyst til å smake?' }).fill('riesling'); + await page.getByRole('combobox', { name: 'Hva har du lyst til å smake?' }).fill('riesling'); await page.keyboard.press('Enter'); await expect(page).toHaveURL(/\/sok\?q=riesling$/); await expect(page.getByRole('heading', { level: 1 })).toBeFocused(); diff --git a/frontend/e2e/suggestions.spec.ts b/frontend/e2e/suggestions.spec.ts new file mode 100644 index 0000000..773ecc8 --- /dev/null +++ b/frontend/e2e/suggestions.spec.ts @@ -0,0 +1,131 @@ +import AxeBuilder from '@axe-core/playwright'; +import { expect, test, type Page } from '@playwright/test'; +import { stubGraphQL } from './support/graphql'; + +/* + * E2E for the search suggestions on the landing page. Runs against `vite preview` with a + * stubbed GraphQL API. The landing page data itself is not stubbed: the suggestions must + * work no matter what the rest of the page does. + */ +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, 'Les Plateaux Pinot Noir'), + wine(4, 'Pinot Noir Estate'), + wine(5, 'Vieille Vigne Pinot Noir'), +]; + +async function stubSuggestions(page: Page) { + const operations = await stubGraphQL(page, { + WineSuggestions: () => ({ + data: { + wines: { + __typename: 'WineConnection', + totalCount: 18, + edges: WINES.map((node) => ({ __typename: 'WineEdge', node })), + }, + }, + }), + Wine: () => ({ data: { wine: null } }), + }); + return () => operations.filter((name) => name === 'WineSuggestions').length; +} + +const combobox = (page: Page) => + page.getByRole('combobox', { name: 'Hva har du lyst til å smake?' }); + +test.describe('Søkeforslag på forsiden', () => { + let suggestionRequests: () => number; + + test.beforeEach(async ({ page }) => { + suggestionRequests = await stubSuggestions(page); + await page.goto('./'); + }); + + test('skriv «noir pinot», velg en vin med piltastene og havn på vinsiden', async ({ page }) => { + await combobox(page).pressSequentially('noir pinot', { delay: 40 }); + + await expect(page.getByRole('option')).toHaveCount(6); + expect(suggestionRequests()).toBe(1); + + await page.keyboard.press('ArrowDown'); + await page.keyboard.press('ArrowDown'); + await page.keyboard.press('Enter'); + + await expect(page).toHaveURL(/\/vin\/2$/); + }); + + test('Enter uten valgt forslag er et vanlig søk', async ({ page }) => { + await combobox(page).pressSequentially('pinot', { delay: 40 }); + await expect(page.getByRole('option')).toHaveCount(6); + + await page.keyboard.press('Enter'); + + await expect(page).toHaveURL(/\/sok\?q=pinot$/); + }); + + test('alle forslagene er synlige og ikke skjult av siden rundt', async ({ page }) => { + // Tall enough that nothing needs to scroll: scrolling into view can move the content + // inside a clipping section, which would hide the very problem this test looks for. + const { width } = page.viewportSize() ?? { width: 1280 }; + await page.setViewportSize({ width, height: 1400 }); + await combobox(page).pressSequentially('pinot', { delay: 40 }); + const last = page.getByRole('option', { name: 'Se alle 18 treff for «pinot»' }); + await expect(last).toBeAttached(); + + // A clipped element still has a size, so check what is actually drawn on that spot. + const box = await last.boundingBox(); + if (!box) throw new Error('The last option has no size.'); + const drawn = await page.evaluate( + ({ x, y }) => document.elementFromPoint(x, y)?.closest('[role="option"]')?.textContent, + { x: box.x + box.width / 2, y: box.y + box.height / 2 }, + ); + expect(drawn).toContain('Se alle 18 treff'); + + await last.click(); + await expect(page).toHaveURL(/\/sok\?q=pinot$/); + }); + + test('Escape lukker forslagene, og fokus blir i søkefeltet', async ({ page }) => { + await combobox(page).pressSequentially('pinot', { delay: 40 }); + await expect(page.getByRole('option')).toHaveCount(6); + + await page.keyboard.press('Escape'); + + await expect(page.getByRole('option')).toHaveCount(0); + await expect(combobox(page)).toBeFocused(); + await expect(combobox(page)).toHaveValue('pinot'); + }); + + test('har ingen axe-brudd med åpne forslag', async ({ page }) => { + await combobox(page).pressSequentially('pinot', { delay: 40 }); + await expect(page.getByRole('option')).toHaveCount(6); + + const axe = await new AxeBuilder({ page }) + .include('form[role="search"]') + .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']) + .analyze(); + expect(axe.violations).toEqual([]); + }); + + test('har ingen horisontal scroll ved 320 px med åpne forslag', async ({ page }) => { + await page.setViewportSize({ width: 320, height: 640 }); + await combobox(page).pressSequentially('pinot', { delay: 40 }); + await expect(page.getByRole('option')).toHaveCount(6); + + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth > window.innerWidth, + ); + expect(overflow).toBe(false); + }); +}); diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 3b936cc..00a55cf 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.0", "dependencies": { "@apollo/client": "^4.3.7", + "downshift": "^9.5.0", "graphql": "^16.15.0", "react": "^19.2.8", "react-dom": "^19.2.8", @@ -354,7 +355,6 @@ "version": "7.29.10", "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", - "dev": true, "license": "MIT", "engines": { "node": ">=6.9.0" @@ -2151,6 +2151,12 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/compute-scroll-into-view": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.2.2.tgz", + "integrity": "sha512-X+jf3y2j3TbtxA3fq3/kBNiSnD1QlIChiIQdAc2Yo1LtOc0yjO1TzgxWJf8PwtKPGgSvSfWUlVvrb7vGx1eYWA==", + "license": "MIT" + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -2296,6 +2302,28 @@ "dev": true, "license": "MIT" }, + "node_modules/downshift": { + "version": "9.5.0", + "resolved": "https://registry.npmjs.org/downshift/-/downshift-9.5.0.tgz", + "integrity": "sha512-3a7DhJgV9qS30gALEXs/bS0O1MzvtUHHBrhtaNIHLp6dYE0S5e9wr26KAMzcuqWUW8JlltUR0THg4Ys3AmFs9Q==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.28.6", + "compute-scroll-into-view": "^3.1.1", + "prop-types": "^15.8.1", + "react-is": "^18.2.0", + "tslib": "^2.8.1" + }, + "peerDependencies": { + "react": ">=16.12.0" + } + }, + "node_modules/downshift/node_modules/react-is": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "license": "MIT" + }, "node_modules/electron-to-chromium": { "version": "1.5.439", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.439.tgz", @@ -2845,7 +2873,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, "license": "MIT" }, "node_modules/jsdom": { @@ -3246,6 +3273,18 @@ "dev": true, "license": "MIT" }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, "node_modules/lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", @@ -3366,6 +3405,15 @@ "node": ">=18" } }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/obug": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", @@ -3608,6 +3656,23 @@ "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" } }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/prop-types/node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "license": "MIT" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index fe818fb..ed81bfa 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -20,6 +20,7 @@ }, "dependencies": { "@apollo/client": "^4.3.7", + "downshift": "^9.5.0", "graphql": "^16.15.0", "react": "^19.2.8", "react-dom": "^19.2.8", diff --git a/frontend/src/features/landing/LandingView.test.tsx b/frontend/src/features/landing/LandingView.test.tsx index abc2881..cb01f97 100644 --- a/frontend/src/features/landing/LandingView.test.tsx +++ b/frontend/src/features/landing/LandingView.test.tsx @@ -37,7 +37,7 @@ describe('LandingView – innhold', () => { it('har et stort søkefelt som sender til søkesiden', async () => { const { user } = renderLoaded(); await user.type( - screen.getByRole('searchbox', { name: 'Hva har du lyst til å smake?' }), + screen.getByRole('combobox', { name: 'Hva har du lyst til å smake?' }), 'barolo{Enter}', ); expect(screen.getByTestId('location')).toHaveTextContent('/sok?q=barolo'); @@ -112,7 +112,7 @@ describe('LandingView – tilstander', () => { renderWithRouter(); expect(screen.getByRole('status')).toHaveTextContent('Laster viner'); expect( - screen.getByRole('searchbox', { name: 'Hva har du lyst til å smake?' }), + screen.getByRole('combobox', { name: 'Hva har du lyst til å smake?' }), ).toBeInTheDocument(); expect(screen.getAllByTestId('skeleton').length).toBeGreaterThan(0); }); diff --git a/frontend/src/features/landing/api/suggestionsQuery.ts b/frontend/src/features/landing/api/suggestionsQuery.ts new file mode 100644 index 0000000..2b18456 --- /dev/null +++ b/frontend/src/features/landing/api/suggestionsQuery.ts @@ -0,0 +1,20 @@ +import { gql } from '@apollo/client'; + +/** A few wines for the search suggestions, with only the fields the list shows. */ +export const SUGGESTIONS_QUERY = gql` + query WineSuggestions($search: String!, $first: Int!) { + wines(search: $search, first: $first, sort: TOP_RATED) { + totalCount + edges { + node { + id + name + type + wineryName + country + countryCode + } + } + } + } +`; diff --git a/frontend/src/features/landing/api/useWineSuggestions.ts b/frontend/src/features/landing/api/useWineSuggestions.ts new file mode 100644 index 0000000..f08cc52 --- /dev/null +++ b/frontend/src/features/landing/api/useWineSuggestions.ts @@ -0,0 +1,74 @@ +import { useQuery } from '@apollo/client/react'; +import { useDebouncedValue } from '../../../hooks/useDebouncedValue'; +import { formatCountry } from '../../../lib/format'; +import { toWineType } from '../../../lib/mapWine'; +import type { WineType } from '../../../lib/types'; +import { SUGGESTIONS_QUERY } from './suggestionsQuery'; + +/** Wait this long after the last key press before asking for suggestions. */ +const DEBOUNCE_MS = 300; +/** One letter matches almost every wine, so suggestions start at two. */ +export const MIN_LENGTH = 2; +export const SUGGESTION_COUNT = 5; + +interface SuggestionsData { + wines: { + totalCount: number; + edges: { + node: { + id: string; + name: string; + type: string; + wineryName: string | null; + country: string | null; + countryCode: string | null; + }; + }[]; + }; +} + +export interface WineSuggestion { + id: string; + name: string; + type: WineType; + /** «Frankrike · Produsent», or as much of it as the wine has. */ + details: string; +} + +export interface WineSuggestionsResult { + /** The text the suggestions are for. Lags behind what the user types, by the debounce. */ + term: string; + wines: WineSuggestion[]; + totalCount: number | undefined; + loading: boolean; + error: Error | undefined; +} + +export function useWineSuggestions(text: string): WineSuggestionsResult { + const term = useDebouncedValue(text.trim().replace(/\s+/g, ' '), DEBOUNCE_MS); + const skip = term.length < MIN_LENGTH; + const { data, previousData, loading, error } = useQuery(SUGGESTIONS_QUERY, { + variables: { search: term, first: SUGGESTION_COUNT }, + skip, + }); + + // The old suggestions stay while the next ones load, so the list does not flicker. + const result = skip ? undefined : (data ?? previousData); + const wines = (result?.wines.edges ?? []).flatMap(({ node }): WineSuggestion[] => { + const type = toWineType(node.type); + if (!type) return []; + const country = node.countryCode + ? formatCountry(node.countryCode, node.country ?? '') + : node.country; + const details = [country, node.wineryName].filter(Boolean).join(' · '); + return [{ id: node.id, name: node.name, type, details }]; + }); + + return { + term: skip ? '' : term, + wines, + totalCount: result?.wines.totalCount, + loading: !skip && loading, + error: skip ? undefined : error, + }; +} diff --git a/frontend/src/features/landing/components/Hero.module.css b/frontend/src/features/landing/components/Hero.module.css index da77a3a..a7e5d4f 100644 --- a/frontend/src/features/landing/components/Hero.module.css +++ b/frontend/src/features/landing/components/Hero.module.css @@ -1,6 +1,8 @@ .hero { position: relative; - overflow: hidden; + /* Clips the bottles sideways, but lets the search suggestions hang below the section. + `hidden` would cut them off, and unlike `hidden`, `clip` does not make the other axis scroll. */ + overflow-x: clip; background: radial-gradient(circle at 85% 20%, rgb(220 193 150 / 0.18), transparent 45%), linear-gradient(180deg, var(--color-brand) 0%, var(--color-brand-strong) 100%); diff --git a/frontend/src/features/landing/components/Hero.tsx b/frontend/src/features/landing/components/Hero.tsx index 5808dd6..647848f 100644 --- a/frontend/src/features/landing/components/Hero.tsx +++ b/frontend/src/features/landing/components/Hero.tsx @@ -1,6 +1,6 @@ import { ChipLink } from '../../../components/ui/Chip'; import { Bottle } from '../../../components/ui/Bottle'; -import { SearchForm } from '../../../components/ui/SearchForm'; +import { HeroSearch } from './HeroSearch'; import { buildSearchUrl } from '../../../lib/searchParams'; import { SUGGESTIONS } from '../suggestions'; import styles from './Hero.module.css'; @@ -20,11 +20,7 @@ export function Hero() {

- +
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 ( +
+ +
+ + { + if (event.key === 'Enter' && highlightedIndex < 0) { + ( + event.nativeEvent as KeyboardEvent & { preventDownshiftDefault?: boolean } + ).preventDownshiftDefault = true; + } + }, + })} + /> + +
+ + {/* Always in the DOM, because Downshift needs the list element even when it is closed. */} +
    + {open && + items.map((item, index) => ( +
  • + {item.kind === 'wine' ? ( + <> + {item.wine.name} + + {[WINE_TYPES[item.wine.type].label, item.wine.details] + .filter(Boolean) + .join(' · ')} + + + ) : ( + {allLabel(item.query, wines.length, totalCount)} + )} +
  • + ))} +
+ + {/* aria-live, and not role="status", since the landing page already has a status region. */} +

+ {status} +

+
+ ); +} + +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);