diff --git a/README.md b/README.md index ff0a88f..a1f70e8 100644 --- a/README.md +++ b/README.md @@ -1,52 +1,374 @@ # Kork & Krone -A student project for IT2810 Web Development at NTNU. The goal is a searchable -Vinmonopolet catalog with filters, sorting, and product reviews. +**Last updated:** 6 November 2026 +**Submission:** 3 (first complete prototype, beta) +**Status:** In progress. See [Status for submission 3](#status-for-submission-3). -Web application: [Kork & Krone](http://it2810-18.idi.ntnu.no/project2/) -(NTNU network or VPN required). + + +Kork & Krone is a wine review site for students, inspired by Vivino. It is a group project in IT2810 Web Development at NTNU (group T18). + +Students can search, filter and sort a catalogue of wines. Each wine shows two ratings side by side: the community rating from the X-Wines dataset and the rating from other students. Students give their own verdict as a die roll from 1 to 6. + +- **Application:** [it2810-18.idi.ntnu.no/project2/](http://it2810-18.idi.ntnu.no/project2/). Requires the NTNU network or VPN. +- **GraphQL API:** `/project2/graphql` on the VM, `localhost:3001/graphql` locally. + +## Contents + +1. [Status for submission 3](#status-for-submission-3) +2. [Get started](#get-started) +3. [Features](#features) +4. [Architecture and technology choices](#architecture-and-technology-choices) +5. [Data](#data) +6. [Accessibility](#accessibility) +7. [Sustainability](#sustainability) +8. [Testing](#testing) +9. [Code quality and conventions](#code-quality-and-conventions) +10. [Use of AI](#use-of-ai) +11. [Plan ahead](#plan-ahead) +12. [Further documentation](#further-documentation) + +--- + +## Status for submission 3 + +Submission 3 should be the first complete prototype, with search, browsing, sorting and filtering. Due to conflicting schedules and an unexpected need for an API/dataset switch, we are behind where we would want to be. The table shows where each part stands. We continue to work gradually as one does, so reviewers may have different experiences, as well as see changes that are not yet documented, all depending on when the review is made. + +| Area | Status | Note | +|---|---|---| +| Landing page | Done | Shows real data from the API. Reviews are hidden until the API supports them | +| GraphQL API: search, filter, sort, pagination | Done | Queries `wines`, `wine` and `filterOptions` | +| Database schema and X-Wines Test import | Done | 100 wines and 1 000 ratings | +| 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 | +| Wine detail page | Planned | Placeholder page at `/vin/:id` | +| Student reviews (stored in the database) | Planned | | +| Larger dataset on the VM | Planned | | +| Continuous integration (CI) | Not yet started | | + + + +### What we want feedback on + +Although the project is currently a bit behind schedule, we would still like relevant feedback on what is implemented and planned. + +Some suggested options are design and accessibility of the website, API design found in docs/api.md, architectural and technological choices, implemented and planned features and sustainability. -The project has a React/TypeScript frontend and a GraphQL backend (Apollo Server, -TypeScript) on PostgreSQL. The catalog uses the X-Wines dataset. See [API](docs/api.md). ## Get started -Install Node.js 24 or newer. Follow [setup](docs/setup.md) to clone the project, -create a local database, and configure `backend/.env`. +Requires Node.js 24 or newer and PostgreSQL. See [setup](docs/setup.md) and [database](docs/database.md) for details. + +```bash +git clone https://git.ntnu.no/IT2810-H26/T18-Project-2.git +cd T18-Project-2 +npm ci --prefix backend +npm ci --prefix frontend +cp backend/.env.example backend/.env # then set your database password +npm run db:schema --prefix backend +npm run db:seed:test --prefix backend +``` -From the project folder, start the backend: +Start the backend and the frontend in two terminals: ```bash -cd backend -npm start +cd backend && npm run dev # http://localhost:3001/graphql +cd frontend && npm run dev # http://localhost:5173/project2/ ``` -In another terminal, from the project folder, start the frontend: +The landing page needs the backend for wines and categories. Without it, the page shows an error message with a "Prøv igjen" button. + +To deploy on the VM, see the [VM guide](docs/vm.md). + +## Features + +This section describes what users can do. "Backend" means the API supports the feature. "UI" means it is visible on the site. + +| Feature | Backend | UI | Description | +|---|---|---|---| +| Search | Done | Planned | Ignores case and accents. Matches name, winery, region and grapes | +| 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 | +| 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 | +| User | Planned | Planned | Login or anonymous ID stored in browser | + + +## Architecture and technology choices + +``` +Browser (React) + | GraphQL over HTTP (Apollo Client) + v +Apache on the VM: serves the built frontend and forwards /project2/graphql + | + v +Apollo Server on Express (Node.js, TypeScript) + | SQL (pg) + v +PostgreSQL with pg_trgm +``` + +Each row explains what we chose, why, and what else we considered. Added as the group makes a new choice. + +| Area | Choice | Why | Alternatives considered | +|---|---|---|---| +| Frontend | React 19, TypeScript, Vite | Required by the course. Vite gives fast builds and splits code per page | – | +| Routing | React Router | Search state lives in the URL, so it can be shared and survives reloads | Keeping state only in React | +| State management | Apollo Client cache and URL parameters | Server data is kept in the Apollo cache. User choices are kept in the URL. Nothing is left that needs a global store | Redux, Zustand | +| 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 | +| Search, filtering and sorting | In the database | Scales to large datasets. The frontend never loads the whole catalogue | Filtering in the browser | +| 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) | + + + +See [API](docs/api.md) for the schema and example queries. + +## Data + +We use the [X-Wines](https://github.com/rogerioxavier/X-Wines) dataset. It is released under CC0 (public domain). It contains 100 646 wines and about 21 million real ratings, with grapes, alcohol content, country, region and food pairing. + +**Why not Vinmonopolet?** We first planned to use the Vinmonopolet API. The open API only provides product ID, name and date of change. That is too little for filtering and sorting. The import script in `scripts/` is kept for a possible later feature. + +| Version | Wines | Ratings | Used for | +|---|---|---|---| +| Test | 100 | 1 000 | Local development and automated tests | +| Slim | 1 007 | 150 000 | Planned for the VM | +| Full | 100 646 | about 21 million | Planned for load testing and to show that the solution scales | + +The VM and local development currently use the Test version. We plan to load Slim on the VM, because it gives +enough wines to make search, filters and pagination meaningful, and it imports quickly. + +We plan to use Full locally to show that the solution scales. Search, filtering, sorting and pagination run in +PostgreSQL with indexes (a trigram index for text search and B-tree and GIN indexes for sorting and filters), +so the frontend never loads more than one page of results. When Full is loaded, we will add the import time, +the database size and the measured search time (with `EXPLAIN ANALYZE`) here. + +This is subject to change as needed. + +Citation: de Azambuja, R.X.; Morais, A.J.; Filipe, V. X-Wines: A Wine Dataset for Recommender Systems and Machine Learning. *Big Data Cogn. Comput.* 2023, 7, 20. https://doi.org/10.3390/bdcc7010020 + +## Accessibility + +Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing, motor skills and cognition. + +### Implemented + +- Semantic HTML: landmarks (`header`, `nav`, `main`, `footer`), one `h1` per page, lists for groups of cards, and `
` for each wine card. We try to use `div` and `span` only for layout. See [conventions](#code-quality-and-conventions). +- A skip link to the main content, and visible focus on all interactive elements. +- After navigation, focus moves to the page's `h1`. Screen reader users then hear that the page has changed. +- Ratings are always shown as text, for example "4,6 av 5 · 23 dommer". The die has a text alternative for screen readers. +- Loading states are announced in a live region. Errors use `role="alert"` and have a "Prøv igjen" button. +- Click targets are at least 44 × 44 px. +- Animations respect `prefers-reduced-motion`. +- No horizontal scrolling at 320 px width (WCAG 1.4.10, reflow). +- Text contrast is at least 4.9:1 in both light and dark mode. +- `lang="nb"` and a separate page title for each page. + +### How we check it + +- vitest-axe on components and pages. +- Playwright with axe-core against WCAG 2.1 A and AA, on desktop and mobile. +- An automated test for reflow at 320 px. +- Manual testing with only the keyboard. + + + +### Some known gaps + +- The search page, filters 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. + +## Sustainability + +We follow the principle from the course: measure, set a budget and show the numbers. + +### Design choices + +- SVG bottle illustrations instead of product photos. One small reusable component replaces thousands of images. +- System fonts. The site downloads no web fonts. +- Dark mode via `prefers-color-scheme`. This uses less energy on OLED screens. +- A "Last inn flere" button instead of infinite scrolling. Data is only loaded when the user asks for it. + +### Technical choices + +- Code splitting per page with `React.lazy`. The landing page does not load the code for search and the detail page. +- 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. + +**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 | +| 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 | +| CO2 per visit | Not decided | Not measured yet | | CO2.js (Sustainable Web Design model) with the transferred bytes | + +The search scenario is: open the landing page, search for "riesling", filter on red wine, and load one more page of results. +Lighthouse performance is low mainly because Apache does not compress files or set cache headers yet, +and because the test was run over VPN. These are the "before" numbers. We will measure again after enabling compression. + +## Testing + +| 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 (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) | +| 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 %. + +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. +Run `npm run test:coverage` in `frontend/` to see the full report. + +### Run the tests ```bash cd frontend -npm run dev +npm run test:run +npm run e2e # first time: npx playwright install chromium + +cd ../backend +npm test ``` -## Access +## Code quality and conventions + +### Workflow + +- One issue per task and one branch per issue. Changes go through a pull request. +- Make tests and preferably update documentation as you go. +- Another group member must review every pull request (`.github/CODEOWNERS`). +- Before a pull request, run lint, Prettier, type checking, tests and build. See [workflow](docs/workflow.md). + +### Tools + +- ESLint with TypeScript and React Hooks rules, and Prettier for formatting. +- Strict TypeScript in both frontend and backend. + + + +### Code structure + +``` +frontend/src/ + app/ routes and the app shell + components/ shared components (layout/ and ui/) + features/ one folder per feature: landing/, search/, ... + hooks/ shared React hooks + lib/ pure functions and types + styles/ design tokens and global CSS +backend/src/ + schema.ts GraphQL schema + resolvers.ts GraphQL resolvers + wine-query.ts builds the SQL for search, filtering and sorting + scripts/ database schema and import of X-Wines +``` + +### Language + +- English for everything in code and on git: names, comments, tests, commits, pull requests and documentation. +- Norwegian (bokmål) for everything users see or hear: text in the interface, error messages, `aria-label`, `alt` text and page titles. +- Numbers and dates are formatted with `Intl` and the `nb-NO` locale. + +### Semantic HTML + +- We always try to use the semantic element that exists for the purpose: `button`, `a`, `label`, `fieldset`, `ul`, `article`, `time` and so on. +- `div` and `span` are only used for layout. If we use them where a semantic element could fit, a code comment should explain why. + + + +## Use of AI + +We use AI tools as a sparring partner and as a code assistant. AI-generated code goes through the same review as other code, and we run and test it before it is merged. +Claude and ChatGPT are the main models used. The usecases for the AI tools are as follows: +- Help with planning and structuring +- Generate specified code for specified functionality +- Help with testing and fail searching +- Help with reviewing +- Help with proper documentation +- Help with keeping us in line with project guidelines + + +## Plan ahead + +### 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. +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. +6. [ ] Start the backend on the VM and load the dataset. + +### Then: towards the next submission -- VM: [it2810-18.idi.ntnu.no/project2/](http://it2810-18.idi.ntnu.no/project2/). -- Local frontend: [localhost:5173](http://localhost:5173/). -- Local backend: [localhost:3001](http://localhost:3001/). Shows database information as plain text. +- [ ] Student reviews: GraphQL mutation, database table, validation, and the new rating shown at once. +- [ ] Wishlist stored in the backend. +- [ ] Larger dataset on the VM, and a load test with the full dataset. +- [ ] CI, an enforced coverage threshold, and eslint-plugin-jsx-a11y. +- [ ] Measure sustainability and fill in the budget table. +- [ ] Screen reader test and a written reflection on the use of AI. -Use the NTNU network or VPN to access the VM. +### Some known issues -## Deployment +- 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. -Follow the [VM guide](docs/vm.md) to publish the frontend with `npm run buildvm`, -configure Apache, and start or stop the backend with `nohup`. -Run frontend npm commands from `frontend/`. + -## Documentation +## Further documentation -- [Setup](docs/setup.md): Git, dependencies, `.env`, and local startup. -- [Database](docs/database.md): PostgreSQL on macOS, Windows, and Ubuntu, plus a connection check. -- [VM](docs/vm.md): Server setup, frontend deployment, backend start/stop, and logs. -- [Tasks](docs/tasks.md): Project scope, requirements, and sketches. -- [Workflow](docs/workflow.md): Branches, reviews, and checks. -- [API](docs/api.md): GraphQL queries, test data, and the X-Wines citation. +- [Setup](docs/setup.md): Git, dependencies, `.env` and local start +- [Database](docs/database.md): PostgreSQL on macOS, Windows and Ubuntu +- [VM](docs/vm.md): deployment, Apache and running the backend with `nohup` +- [API](docs/api.md): GraphQL queries, test data and the X-Wines citation +- [Workflow](docs/workflow.md): branches, reviews and checks +- [Tasks](docs/tasks.md): requirements and sketches \ No newline at end of file diff --git a/frontend/e2e/landing.spec.ts b/frontend/e2e/landing.spec.ts index 7485388..19ddd6d 100644 --- a/frontend/e2e/landing.spec.ts +++ b/frontend/e2e/landing.spec.ts @@ -3,13 +3,54 @@ import { expect, test } from '@playwright/test'; /* * E2E for forsiden. Kjøres mot `vite preview` (se playwright.config.ts). - * Når backend er koblet på, kjør mot test-databasen med X-Wines Test. + * GraphQL-svaret er stubbet, så testene ikke trenger en kjørende backend. */ +const wines = Array.from({ length: 6 }, (_, i) => ({ + __typename: 'Wine', + id: String(i + 1), + name: `Testvin ${i + 1}`, + type: 'Red', + grapes: ['Pinot Noir'], + country: 'France', + wineryName: 'Testprodusent', + communityRating: 4.5, + communityRatingCount: 10, +})); + +const landingResponse = { + data: { + topRated: { + __typename: 'WineConnection', + totalCount: 100, + edges: wines.map((node) => ({ __typename: 'WineEdge', node })), + }, + filterOptions: { + __typename: 'FilterOptions', + types: [{ __typename: 'FilterOption', value: 'Red', count: 100 }], + countries: [{ __typename: 'FilterOption', value: 'FR' }], + }, + }, +}; + test.describe('Forsiden', () => { + let graphqlRequests = 0; + test.beforeEach(async ({ page }) => { + graphqlRequests = 0; + await page.route('**/project2/graphql', (route) => { + graphqlRequests += 1; + return route.fulfill({ json: landingResponse }); + }); await page.goto('./'); }); + test('henter hele forsiden i én GraphQL-forespørsel', async ({ page }) => { + await expect( + page.getByRole('region', { name: 'Best vurdert' }).getByRole('article'), + ).toHaveCount(6); + expect(graphqlRequests).toBe(1); + }); + test('forklarer hva siden er og har riktig tittel', async ({ page }) => { await expect(page).toHaveTitle(/Kork & Krone/); await expect(page.getByRole('heading', { level: 1 })).toHaveText( @@ -32,7 +73,7 @@ test.describe('Forsiden', () => { test('har ingen axe-brudd (WCAG 2.1 AA)', async ({ page }) => { await expect( - page.getByRole('region', { name: 'Medstudentenes favoritter' }).getByRole('article'), + page.getByRole('region', { name: 'Best vurdert' }).getByRole('article'), ).toHaveCount(6); const results = await new AxeBuilder({ page }) .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 1fc2a06..f5cf5ad 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -8,6 +8,8 @@ "name": "t18-project-2", "version": "0.0.0", "dependencies": { + "@apollo/client": "^4.3.7", + "graphql": "^16.15.0", "react": "^19.2.8", "react-dom": "^19.2.8", "react-router": "^8.5.1" @@ -49,6 +51,43 @@ "dev": true, "license": "MIT" }, + "node_modules/@apollo/client": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/@apollo/client/-/client-4.3.7.tgz", + "integrity": "sha512-s+aetmVMhR/UkpsnyKqJb9uQBSv0c42Nb2S517H4Zbqc7GTdKNH/Su+Zv6euR+OHL1YosOhUm3DhvuQUi8Mxtg==", + "license": "MIT", + "dependencies": { + "@graphql-typed-document-node/core": "^3.1.1", + "@wry/caches": "^1.0.0", + "@wry/equality": "^0.5.6", + "@wry/trie": "^0.5.0", + "graphql-tag": "^2.12.6", + "optimism": "^0.18.0", + "tslib": "^2.3.0" + }, + "peerDependencies": { + "graphql": "^16.0.0 || ^17.0.0", + "graphql-ws": "^5.5.5 || ^6.0.3", + "react": "^17.0.0 || ^18.0.0 || >=19.0.0-rc", + "react-dom": "^17.0.0 || ^18.0.0 || >=19.0.0-rc", + "rxjs": "^7.3.0", + "subscriptions-transport-ws": "^0.9.0 || ^0.11.0" + }, + "peerDependenciesMeta": { + "graphql-ws": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "subscriptions-transport-ws": { + "optional": true + } + } + }, "node_modules/@asamuzakjp/css-color": { "version": "7.1.9", "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.9.tgz", @@ -701,6 +740,15 @@ } } }, + "node_modules/@graphql-typed-document-node/core": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/@graphql-typed-document-node/core/-/core-3.2.0.tgz", + "integrity": "sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==", + "license": "MIT", + "peerDependencies": { + "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" + } + }, "node_modules/@humanfs/core": { "version": "0.19.2", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", @@ -1766,6 +1814,54 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@wry/caches": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@wry/caches/-/caches-1.0.1.tgz", + "integrity": "sha512-bXuaUNLVVkD20wcGBWRyo7j9N3TxePEWFZj2Y+r9OoUzfqmavM84+mFykRicNsBqatba5JLay1t48wxaXaWnlA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@wry/context": { + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/@wry/context/-/context-0.7.4.tgz", + "integrity": "sha512-jmT7Sb4ZQWI5iyu3lobQxICu2nC/vbUhP0vIdd6tHC9PTfenmRmuIFqktc6GH9cgi+ZHnsLWPvfSvc4DrYmKiQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@wry/equality": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/@wry/equality/-/equality-0.5.7.tgz", + "integrity": "sha512-BRFORjsTuQv5gxcXsuDXx6oGRhuVsEGwZy6LOzRRfgu+eSfxbhUQ9L9YtSEIuIjY/o7g3iWFjrc5eSY1GXP2Dw==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@wry/trie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@wry/trie/-/trie-0.5.0.tgz", + "integrity": "sha512-FNoYzHawTMk/6KMQoEG5O4PuioX19UbwdQKF44yw0nLfOypfQdjtfZzo/UIJWAJ23sNIFbD1Ug9lbaDGMwbqQA==", + "license": "MIT", + "dependencies": { + "tslib": "^2.3.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/acorn": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", @@ -2560,6 +2656,30 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/graphql": { + "version": "16.15.0", + "resolved": "https://registry.npmjs.org/graphql/-/graphql-16.15.0.tgz", + "integrity": "sha512-32kz9FecohDiC/tgcViwnRXM7HFBVTPiW7pHO+DikKOI5KjhU/jNULOReXsrFqt2WAYbE9xFXsTffJw6iTO8qw==", + "license": "MIT", + "engines": { + "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" + } + }, + "node_modules/graphql-tag": { + "version": "2.12.7", + "resolved": "https://registry.npmjs.org/graphql-tag/-/graphql-tag-2.12.7.tgz", + "integrity": "sha512-xnE/NFzy+0eIesvAsREJZ284zTl/wYuBAvpsFSDhRGRdRHdnE90M21Q3xAWyYInb0J756c6x0pIQ62+vtvOs1Q==", + "license": "MIT", + "dependencies": { + "tslib": "^2.1.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "graphql": "^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" + } + }, "node_modules/hashery": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", @@ -3215,6 +3335,18 @@ "node": ">=12.20.0" } }, + "node_modules/optimism": { + "version": "0.18.1", + "resolved": "https://registry.npmjs.org/optimism/-/optimism-0.18.1.tgz", + "integrity": "sha512-mLXNwWPa9dgFyDqkNi54sjDyNJ9/fTI6WGBLgnXku1vdKY/jovHfZT5r+aiVeFFLOz+foPNOm5YJ4mqgld2GBQ==", + "license": "MIT", + "dependencies": { + "@wry/caches": "^1.0.0", + "@wry/context": "^0.7.0", + "@wry/trie": "^0.5.0", + "tslib": "^2.3.0" + } + }, "node_modules/optionator": { "version": "0.9.4", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", @@ -3564,6 +3696,16 @@ "@rolldown/binding-win32-x64-msvc": "1.2.16" } }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "tslib": "^2.1.0" + } + }, "node_modules/saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", @@ -3751,6 +3893,12 @@ "typescript": ">=4.8.4" } }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD" + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index aa3b70c..f96215a 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -18,6 +18,8 @@ "e2e": "playwright test" }, "dependencies": { + "@apollo/client": "^4.3.7", + "graphql": "^16.15.0", "react": "^19.2.8", "react-dom": "^19.2.8", "react-router": "^8.5.1" diff --git a/frontend/src/components/ui/WineCard.test.tsx b/frontend/src/components/ui/WineCard.test.tsx index c178c5e..e473529 100644 --- a/frontend/src/components/ui/WineCard.test.tsx +++ b/frontend/src/components/ui/WineCard.test.tsx @@ -39,6 +39,12 @@ describe('WineCard', () => { expect(screen.getByText('Ingen dommer ennå')).toBeInTheDocument(); }); + it('skjuler studentraden når vinen ikke har studentdata', () => { + renderWithRouter(); + expect(screen.queryByText('Studenter')).not.toBeInTheDocument(); + expect(screen.getByText('Fellesskapet')).toBeInTheDocument(); + }); + it('«Vil prøve» er en toggle-knapp med vinnavnet i navnet', async () => { const { user } = renderWithRouter(); const button = screen.getByRole('button', { name: 'Vil prøve Mosel Riesling Kabinett' }); diff --git a/frontend/src/components/ui/WineCard.tsx b/frontend/src/components/ui/WineCard.tsx index bb4711a..6b9fa09 100644 --- a/frontend/src/components/ui/WineCard.tsx +++ b/frontend/src/components/ui/WineCard.tsx @@ -42,12 +42,14 @@ export function WineCard({ wine, headingLevel: Heading = 'h3' }: WineCardProps)

{wine.winery}

-
-
Studenter
-
- {formatRatingSummary(wine.students, { singular: 'dom', plural: 'dommer' })} -
-
+ {wine.students && ( +
+
Studenter
+
+ {formatRatingSummary(wine.students, { singular: 'dom', plural: 'dommer' })} +
+
+ )}
Fellesskapet
{formatRatingSummary(wine.community)}
diff --git a/frontend/src/features/landing/LandingView.test.tsx b/frontend/src/features/landing/LandingView.test.tsx index 1610823..e6592fa 100644 --- a/frontend/src/features/landing/LandingView.test.tsx +++ b/frontend/src/features/landing/LandingView.test.tsx @@ -1,13 +1,13 @@ import { describe, expect, it, vi } from 'vitest'; import { screen, within } from '@testing-library/react'; import { axe } from 'vitest-axe'; +import { landingFixture } from '../../test/landingFixture'; import { renderWithRouter } from '../../test/render'; -import { mockLandingData } from './api/mockLanding'; import { LandingView } from './LandingView'; const now = new Date('2026-10-30T12:00:00Z'); -function renderLoaded(data = mockLandingData) { +function renderLoaded(data = landingFixture) { return renderWithRouter(); } @@ -29,7 +29,7 @@ describe('LandingView – innhold', () => { it('har ett h1 og seksjoner med h2', () => { renderLoaded(); expect(screen.getAllByRole('heading', { level: 1 })).toHaveLength(1); - for (const name of ['Utforsk etter type', 'Medstudentenes favoritter', 'Nylig dømt']) { + for (const name of ['Utforsk etter type', 'Best vurdert', 'Nylig dømt']) { expect(screen.getByRole('region', { name })).toBeInTheDocument(); } }); @@ -66,7 +66,7 @@ describe('LandingView – innhold', () => { it('skjuler kategorier uten viner', () => { renderLoaded({ - ...mockLandingData, + ...landingFixture, categories: [ { type: 'RED', count: 10 }, { type: 'FORTIFIED', count: 0 }, @@ -78,7 +78,7 @@ describe('LandingView – innhold', () => { it('viser seks favoritter som vinkort', () => { renderLoaded(); - const region = screen.getByRole('region', { name: 'Medstudentenes favoritter' }); + const region = screen.getByRole('region', { name: 'Best vurdert' }); expect(within(region).getAllByRole('article')).toHaveLength(6); expect(within(region).getByRole('link', { name: 'Se hele topplisten' })).toHaveAttribute( 'href', @@ -103,14 +103,14 @@ describe('LandingView – innhold', () => { it('viser nøkkeltall', () => { renderLoaded(); expect(screen.getByText('viner å utforske')).toBeInTheDocument(); - expect(screen.getByText('dommer fra studenter')).toBeInTheDocument(); + expect(screen.getByText('land representert')).toBeInTheDocument(); }); }); describe('LandingView – tilstander', () => { it('viser lastetilstand i en live-region, men hero og søk med én gang', () => { renderWithRouter(); - expect(screen.getByRole('status')).toHaveTextContent('Laster favoritter og nye dommer'); + expect(screen.getByRole('status')).toHaveTextContent('Laster viner'); expect( screen.getByRole('searchbox', { name: 'Hva har du lyst til å smake?' }), ).toBeInTheDocument(); @@ -127,15 +127,24 @@ describe('LandingView – tilstander', () => { refetch={refetch} />, ); - expect(screen.getByRole('alert')).toHaveTextContent('Vi fikk ikke hentet favorittene'); + expect(screen.getByRole('alert')).toHaveTextContent('Vi fikk ikke hentet vinene'); await user.click(screen.getByRole('button', { name: 'Prøv igjen' })); expect(refetch).toHaveBeenCalledOnce(); }); - it('har tomtilstander når det ikke finnes data ennå', () => { - renderLoaded({ ...mockLandingData, topRated: [], recentReviews: [] }); - expect(screen.getByText('Ingen viner har fått nok dommer ennå.')).toBeInTheDocument(); - expect(screen.getByText('Ingen har gitt en dom ennå. Bli den første!')).toBeInTheDocument(); + it('har tomtilstand når det ikke finnes viner', () => { + renderLoaded({ ...landingFixture, topRated: [] }); + expect(screen.getByText('Vi fant ingen viner å vise akkurat nå.')).toBeInTheDocument(); + }); + + it('skjuler «Nylig dømt» når det ikke finnes dommer', () => { + renderLoaded({ ...landingFixture, recentReviews: [] }); + expect(screen.queryByRole('region', { name: 'Nylig dømt' })).not.toBeInTheDocument(); + }); + + it('viser ikke skjelett for «Nylig dømt» mens data lastes', () => { + renderWithRouter(); + expect(screen.queryByRole('region', { name: 'Nylig dømt' })).not.toBeInTheDocument(); }); }); diff --git a/frontend/src/features/landing/LandingView.tsx b/frontend/src/features/landing/LandingView.tsx index 7c7e7df..041698a 100644 --- a/frontend/src/features/landing/LandingView.tsx +++ b/frontend/src/features/landing/LandingView.tsx @@ -29,7 +29,7 @@ export function LandingView({ data, loading, error, refetch, now }: LandingViewP {/* Live-region finnes alltid i DOM-en, så endringer annonseres (WCAG 4.1.3). */}

- {loading ? 'Laster favoritter og nye dommer …' : ''} + {loading ? 'Laster viner …' : ''}

{data && } @@ -38,7 +38,7 @@ export function LandingView({ data, loading, error, refetch, now }: LandingViewP {error ? (
-

Vi fikk ikke hentet favorittene og de nyeste dommene akkurat nå.

+

Vi fikk ikke hentet vinene akkurat nå.

{refetch && (