diff --git a/README.md b/README.md index 477fc1e..9824fe7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Kork & Krone -**Last updated:** 11 November 2026 +**Last updated:** 12 November 2026 **Submission:** 3 (first complete prototype, beta) **Status:** In progress. See [Status for submission 3](#status-for-submission-3). @@ -16,7 +16,7 @@ Kork & Krone is a wine review site for students, inspired by Vivino. It is a gro The app is in Norwegian, because its users are Norwegian students. The code and the documentation are in English, as is common in software projects. -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. +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 1 to 5 stars. - **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. @@ -44,7 +44,7 @@ Submission 3 should be the first complete prototype, with search, browsing, sort | Area | Status | Note | |---|---|---| -| Landing page | Done | Shows real data from the API. Reviews are hidden until the API supports them | +| Landing page | Done | Shows real data from the API, including the newest student reviews under «Nylig dømt» | | 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 | @@ -52,8 +52,8 @@ Submission 3 should be the first complete prototype, with search, browsing, sort | Apollo Client in the frontend | Done | | | Search page with results | Done | Search with debounce, number of hits and "Last inn flere" at `/sok` | | Filtering and sorting in the user interface | Done | Filter panel, active filters and sorting on `/sok`. Needs the new backend on the VM | -| Wine detail page | Done | Facts, food pairing and rating at `/vin/:id`. Student reviews are added with the reviews feature | -| Student reviews (stored in the database) | Planned | | +| Wine detail page | Done | Facts, food pairing, the community rating and student reviews at `/vin/:id`. Student reviews are added with the reviews feature | +| Student reviews (stored in the database) | Done | 1–5 stars and an optional comment, saved and shown at once on the wine page | | Larger dataset on the VM | Done | Slim version: 1 007 wines and 150 000 ratings | | Continuous integration (CI) | Not yet started | | @@ -105,10 +105,10 @@ This section describes what users can do. "Backend" means the API supports the f | 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 | | Search state in the URL | Not needed | Done | `?q=&type=&land=&drue=&mat=&vurdering=&alkohol=&sort=`. Survives reloads. Typing replaces the history entry, so the back button leaves the search instead of stepping through every word | -| Wine detail page | Done (`wine(id)`) | Done | Name, winery, region, grapes, alcohol, body, acidity, vintages and food pairing in Norwegian. Grapes and food link to the search. Student reviews are planned | -| Student reviews | Planned | Planned | Die roll from 1 to 6 and an optional comment, stored in PostgreSQL, the new rating is shown at once without a reload (Apollo cache update) | +| Wine detail page | Done (`wine(id)`) | Done | Name, winery, region, grapes, alcohol, body, acidity, vintages and food pairing in Norwegian. Grapes and food link to the search. | +| Student reviews | Done | Done | 1–5 stars and an optional comment, stored in PostgreSQL. The average and the list update at once without a reload. One review per student per wine | | 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 | +| User | Done (Anonymous ID) | Done | An anonymous ID stored in browser until we have login (#29) | ## Architecture and technology choices @@ -354,7 +354,7 @@ Claude and ChatGPT are the main models used. The usecases for the AI tools are a ### Then: towards the next submission -- [ ] Student reviews: GraphQL mutation, database table, validation, and the new rating shown at once. +- [x] Student reviews: GraphQL mutation, database table, validation, and the new rating shown at once. - [ ] Wishlist stored in the backend. - [x] Larger dataset on the VM. - [ ] Load test with the Full dataset. diff --git a/backend/src/schema.ts b/backend/src/schema.ts index 5f8cf93..b5710fa 100644 --- a/backend/src/schema.ts +++ b/backend/src/schema.ts @@ -86,7 +86,7 @@ export const typeDefs = `#graphql type Review { id: ID! - "Rating 0 to 5." + "Rating 1 to 5." rating: Int! comment: String "Display name such as 'Student #4821'. The user ID is never shown." diff --git a/docs/api.md b/docs/api.md index 43ae1b2..387f5b9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -56,8 +56,8 @@ During development, Vite forwards `/graphql` to the backend. On the VM, Apache f ## Student reviews -A review is a die roll from 1 to 6 and an optional comment (max 500 characters). -There is no login yet, so the frontend creates a random UUID once (`crypto.randomUUID()`), +A review is 1 to 5 stars and an optional comment (max 500 characters). +There is no login yet, so the frontend creates a random UUID once (`crypto.randomUUID()`, or random bytes on plain HTTP, where `randomUUID` does not exist), stores it in localStorage and sends it as `userId`. Treat it like a password: the API never returns it, reviews are shown with a display name such as "Student #12". Every student gets their own number the first time they save a review, so two students never share a name. diff --git a/frontend/e2e/landing.spec.ts b/frontend/e2e/landing.spec.ts index 56e630b..ceee7fe 100644 --- a/frontend/e2e/landing.spec.ts +++ b/frontend/e2e/landing.spec.ts @@ -30,6 +30,7 @@ const landingResponse = { types: [{ __typename: 'FilterOption', value: 'Red', count: 100 }], countries: [{ __typename: 'FilterOption', value: 'FR' }], }, + recentReviews: [], }, }; diff --git a/frontend/e2e/wine.spec.ts b/frontend/e2e/wine.spec.ts index 43011c9..204616f 100644 --- a/frontend/e2e/wine.spec.ts +++ b/frontend/e2e/wine.spec.ts @@ -45,6 +45,21 @@ async function stubApi(page: Page) { json: { data: { wine: variables.id === wine.id ? wine : null } }, }); } + if (operationName === 'WineReviews') { + return route.fulfill({ + json: { + data: { + wine: { + __typename: 'Wine', + id: wine.id, + studentRating: { __typename: 'StudentRating', average: null, count: 0 }, + reviews: [], + }, + myReview: null, + }, + }, + }); + } return route.fulfill({ json: searchResult }); }); } diff --git a/frontend/index.html b/frontend/index.html index 7671861..65df8c5 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -14,4 +14,4 @@
- \ No newline at end of file + diff --git a/frontend/src/components/ui/DiceFace.module.css b/frontend/src/components/ui/DiceFace.module.css deleted file mode 100644 index 702ee3e..0000000 --- a/frontend/src/components/ui/DiceFace.module.css +++ /dev/null @@ -1,12 +0,0 @@ -.wrapper { - display: inline-flex; - flex-shrink: 0; -} - -.face { - fill: var(--color-brand); -} - -.pip { - fill: var(--cork-100); -} diff --git a/frontend/src/components/ui/DiceFace.test.tsx b/frontend/src/components/ui/DiceFace.test.tsx deleted file mode 100644 index e449219..0000000 --- a/frontend/src/components/ui/DiceFace.test.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { describe, expect, it } from 'vitest'; -import { render, screen } from '@testing-library/react'; -import { DiceFace } from './DiceFace'; - -describe('DiceFace', () => { - it('har verdien som tekst for skjermlesere', () => { - render(); - expect(screen.getByText('Terningkast 4 av 5')).toBeInTheDocument(); - }); - - it('tegner like mange prikker som verdien', () => { - const { container } = render(); - expect(container.querySelectorAll('circle')).toHaveLength(3); - }); - - it('klemmer verdier utenfor 1–5', () => { - render( - <> - - - , - ); - expect(screen.getByText('Terningkast 5 av 5')).toBeInTheDocument(); - expect(screen.getByText('Terningkast 1 av 5')).toBeInTheDocument(); - }); -}); diff --git a/frontend/src/components/ui/DiceFace.tsx b/frontend/src/components/ui/DiceFace.tsx deleted file mode 100644 index ad41e29..0000000 --- a/frontend/src/components/ui/DiceFace.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import styles from './DiceFace.module.css'; - -/** Prikkposisjoner (3×3-rutenett, 0–8) per terningverdi. */ -const PIPS: Record = { - 1: [4], - 2: [0, 8], - 3: [0, 4, 8], - 4: [0, 2, 6, 8], - 5: [0, 2, 4, 6, 8], -}; - -interface DiceFaceProps { - /** 1–5. Verdier utenfor området klemmes. */ - value: number; - size?: number; -} - -/** - * Terningkast som grafikk + tekst. Grafikken er skjult for skjermlesere; - * teksten «Terningkast 4» er den tilgjengelige verdien. - */ -export function DiceFace({ value, size = 36 }: DiceFaceProps) { - const v = Math.min(5, Math.max(1, Math.round(value))); - return ( - - - Terningkast {v} av 5 - - ); -} diff --git a/frontend/src/components/ui/Stars.module.css b/frontend/src/components/ui/Stars.module.css new file mode 100644 index 0000000..be92e20 --- /dev/null +++ b/frontend/src/components/ui/Stars.module.css @@ -0,0 +1,33 @@ +.stars { + display: inline-flex; + align-items: center; +} + +.icons { + display: inline-flex; + gap: 2px; +} + +.filled, +.empty { + flex-shrink: 0; + stroke-width: 1.5; + stroke-linejoin: round; +} + +.filled { + fill: var(--color-brand); + stroke: var(--color-brand); +} + +.empty { + fill: none; + stroke: var(--color-text-muted); +} + +@media (prefers-color-scheme: dark) { + .filled { + fill: var(--cork-300); + stroke: var(--cork-300); + } +} diff --git a/frontend/src/components/ui/Stars.tsx b/frontend/src/components/ui/Stars.tsx new file mode 100644 index 0000000..b860b28 --- /dev/null +++ b/frontend/src/components/ui/Stars.tsx @@ -0,0 +1,41 @@ +import styles from './Stars.module.css'; + +const STAR_PATH = + 'M12 2.5l2.94 5.96 6.56.95-4.75 4.63 1.12 6.54L12 17.5l-5.87 3.08 1.12-6.54L2.5 9.41l6.56-.95z'; + +/** One star. Hidden from screen readers, so the text next to it is what they read. */ +export function StarIcon({ filled, size = 20 }: { filled: boolean; size?: number }) { + return ( + + ); +} + +interface StarsProps { + /** 1–5. Rounded to whole stars. */ + value: number; + size?: number; +} + +/** A rating as five stars, with the text «4 av 5 stjerner» for screen readers. */ +export function Stars({ value, size = 20 }: StarsProps) { + const filled = Math.min(5, Math.max(0, Math.round(value))); + return ( + + + {filled} av 5 stjerner + + ); +} diff --git a/frontend/src/components/ui/index.ts b/frontend/src/components/ui/index.ts index 214b0c7..f594583 100644 --- a/frontend/src/components/ui/index.ts +++ b/frontend/src/components/ui/index.ts @@ -1,6 +1,6 @@ export { Bottle } from './Bottle'; export { ChipLink } from './Chip'; -export { DiceFace } from './DiceFace'; +export { StarIcon, Stars } from './Stars'; export { ErrorNotice } from './ErrorNotice'; export { HeartIcon } from './HeartIcon'; export { SearchForm } from './SearchForm'; diff --git a/frontend/src/features/landing/LandingPage.test.tsx b/frontend/src/features/landing/LandingPage.test.tsx index 7210ffb..3968019 100644 --- a/frontend/src/features/landing/LandingPage.test.tsx +++ b/frontend/src/features/landing/LandingPage.test.tsx @@ -36,6 +36,7 @@ const mock = { types: [{ __typename: 'FilterOption', value: 'Red', count: 100 }], countries: [{ __typename: 'FilterOption', value: 'FR' }], }, + recentReviews: [], }, }, }; diff --git a/frontend/src/features/landing/LandingView.test.tsx b/frontend/src/features/landing/LandingView.test.tsx index 2808d8f..abc2881 100644 --- a/frontend/src/features/landing/LandingView.test.tsx +++ b/frontend/src/features/landing/LandingView.test.tsx @@ -86,13 +86,13 @@ describe('LandingView – innhold', () => { ); }); - it('viser nye dommer med terningkast, kommentar og tidspunkt', () => { + it('viser nye dommer med stjerner, kommentar og tidspunkt', () => { renderLoaded(); const region = screen.getByRole('region', { name: 'Nylig dømt' }); const items = within(region).getAllByRole('listitem'); expect(items).toHaveLength(5); const first = items[0]; - expect(within(first).getByText('Terningkast 5 av 5')).toBeInTheDocument(); + expect(within(first).getByText('5 av 5 stjerner')).toBeInTheDocument(); expect(within(first).getByRole('link', { name: 'Chianti Classico Riserva' })).toHaveAttribute( 'href', '/vin/111427', diff --git a/frontend/src/features/landing/LandingView.tsx b/frontend/src/features/landing/LandingView.tsx index fdc0e34..cb87bfe 100644 --- a/frontend/src/features/landing/LandingView.tsx +++ b/frontend/src/features/landing/LandingView.tsx @@ -80,7 +80,7 @@ export function LandingView({ data, loading, error, refetch, now }: LandingViewP
diff --git a/frontend/src/features/landing/api/landingQuery.ts b/frontend/src/features/landing/api/landingQuery.ts index 4cd1cb5..b98772f 100644 --- a/frontend/src/features/landing/api/landingQuery.ts +++ b/frontend/src/features/landing/api/landingQuery.ts @@ -31,5 +31,17 @@ export const LANDING_QUERY = gql` value } } + recentReviews(first: 5) { + id + rating + comment + author + createdAt + wine { + id + name + type + } + } } `; diff --git a/frontend/src/features/landing/api/toLandingData.test.ts b/frontend/src/features/landing/api/toLandingData.test.ts index fc2dece..589f6bd 100644 --- a/frontend/src/features/landing/api/toLandingData.test.ts +++ b/frontend/src/features/landing/api/toLandingData.test.ts @@ -25,6 +25,7 @@ const query = (wines: ApiWine[] = [wine('1')]): LandingQueryData => ({ ], countries: [{ value: 'FR' }, { value: 'IT' }], }, + recentReviews: [], }); describe('toLandingData', () => { @@ -45,7 +46,20 @@ describe('toLandingData', () => { expect(topRated.map((w) => w.id)).toEqual(['1', '3']); }); - it('has no recent reviews until the API supports them', () => { - expect(toLandingData(query()).recentReviews).toEqual([]); + it('maps recent reviews and leaves out wines with an unknown type', () => { + const review = (id: string, type: string) => ({ + id, + rating: 4, + comment: null, + author: 'Student #1', + createdAt: '2026-11-12T10:00:00.000Z', + wine: { id: '1', name: 'Wine 1', type }, + }); + const { recentReviews } = toLandingData({ + ...query(), + recentReviews: [review('a', 'Red'), review('b', 'Orange')], + }); + expect(recentReviews.map((r) => r.id)).toEqual(['a']); + expect(recentReviews[0].wine.type).toBe('RED'); }); }); diff --git a/frontend/src/features/landing/api/toLandingData.ts b/frontend/src/features/landing/api/toLandingData.ts index fc39893..b3c4496 100644 --- a/frontend/src/features/landing/api/toLandingData.ts +++ b/frontend/src/features/landing/api/toLandingData.ts @@ -1,5 +1,15 @@ import { toWineSummary, toWineType, type ApiWine } from '../../../lib/mapWine'; -import type { CategoryCount, LandingData, WineSummary } from '../../../lib/types'; +import type { CategoryCount, LandingData, ReviewPreview, WineSummary } from '../../../lib/types'; + +/** A review in «Nylig dømt», as the API returns it. */ +export interface ApiRecentReview { + id: string; + rating: number; + comment: string | null; + author: string; + createdAt: string; + wine: { id: string; name: string; type: string }; +} /** The response from LANDING_QUERY. */ export interface LandingQueryData { @@ -11,10 +21,15 @@ export interface LandingQueryData { types: { value: string; count: number }[]; countries: { value: string }[]; }; + recentReviews: ApiRecentReview[]; } /** Builds the landing page data from the response of LANDING_QUERY. */ -export function toLandingData({ topRated, filterOptions }: LandingQueryData): LandingData { +export function toLandingData({ + topRated, + filterOptions, + recentReviews, +}: LandingQueryData): LandingData { return { stats: { wineCount: topRated.totalCount, @@ -27,6 +42,10 @@ export function toLandingData({ topRated, filterOptions }: LandingQueryData): La topRated: topRated.edges .map(({ node }) => toWineSummary(node)) .filter((wine): wine is WineSummary => wine !== null), - recentReviews: [], // The API has no student reviews yet. + // Reviews of wines with an unknown type are left out, like the wines above. + recentReviews: recentReviews.flatMap((review): ReviewPreview[] => { + const type = toWineType(review.wine.type); + return type ? [{ ...review, wine: { ...review.wine, type } }] : []; + }), }; } diff --git a/frontend/src/features/landing/api/useLandingData.test.tsx b/frontend/src/features/landing/api/useLandingData.test.tsx index 03fcda7..c0f646d 100644 --- a/frontend/src/features/landing/api/useLandingData.test.tsx +++ b/frontend/src/features/landing/api/useLandingData.test.tsx @@ -34,6 +34,7 @@ const result = { types: [{ __typename: 'FilterOption', value: 'White', count: 1 }], countries: [{ __typename: 'FilterOption', value: 'DE' }], }, + recentReviews: [], }, }; diff --git a/frontend/src/features/landing/components/Hero.tsx b/frontend/src/features/landing/components/Hero.tsx index 78e8482..8a6396d 100644 --- a/frontend/src/features/landing/components/Hero.tsx +++ b/frontend/src/features/landing/components/Hero.tsx @@ -16,7 +16,7 @@ export function Hero() {

Kork & Krone samler over 100 000 viner med vurderinger fra et stort vinfellesskap – - og dommene fra studenter som deg. Søk, se hva andre mener, og gi din egen terning. + og dommene fra studenter som deg. Søk, se hva andre mener, og gi din egen dom.

diff --git a/frontend/src/features/landing/components/HowItWorks.tsx b/frontend/src/features/landing/components/HowItWorks.tsx index 6dfe09d..67b8e63 100644 --- a/frontend/src/features/landing/components/HowItWorks.tsx +++ b/frontend/src/features/landing/components/HowItWorks.tsx @@ -11,7 +11,7 @@ const STEPS = [ }, { title: 'Gi din dom', - text: 'Trill terningen fra 1 til 5, skriv en kort kommentar og hjelp neste student.', + text: 'Gi vinen 1 til 5 stjerner, skriv en kort kommentar og hjelp neste student.', }, ]; diff --git a/frontend/src/features/landing/components/RecentReviews.tsx b/frontend/src/features/landing/components/RecentReviews.tsx index e3fe0a4..d2642d4 100644 --- a/frontend/src/features/landing/components/RecentReviews.tsx +++ b/frontend/src/features/landing/components/RecentReviews.tsx @@ -1,5 +1,5 @@ import { Link } from 'react-router'; -import { DiceFace } from '../../../components/ui/DiceFace'; +import { Stars } from '../../../components/ui/Stars'; import { formatRelativeTime } from '../../../lib/format'; import type { ReviewPreview } from '../../../lib/types'; import { WINE_TYPES } from '../../../lib/wineTypes'; @@ -22,7 +22,7 @@ export function RecentReviews({ reviews, now }: RecentReviewsProps) { {reviews.map((review) => (
  • - +

    {review.wine.name} diff --git a/frontend/src/features/wine/WinePage.test.tsx b/frontend/src/features/wine/WinePage.test.tsx index 59c1116..05c8798 100644 --- a/frontend/src/features/wine/WinePage.test.tsx +++ b/frontend/src/features/wine/WinePage.test.tsx @@ -5,8 +5,10 @@ import type { MockLink } from '@apollo/client/testing'; import { MockedProvider } from '@apollo/client/testing/react'; import { MemoryRouter, Route, Routes } from 'react-router'; import { axe } from 'vitest-axe'; +import { USER_ID_KEY } from '../../hooks/useUserId'; import { createApolloCache } from '../../lib/apollo'; import { LocationProbe } from '../../test/LocationProbe'; +import { WINE_REVIEWS_QUERY } from './api/reviewQueries'; import { WINE_QUERY } from './api/wineQuery'; import WinePage from './WinePage'; @@ -44,13 +46,33 @@ const failed: MockLink.MockedResponse = { error: new Error('Nede'), }; +/** A fixed user ID, so the reviews query always has the same variables in these tests. */ +const USER_ID = '3f2a9c1e-8b4d-4e2a-9f1c-2b7d6e5a4c3b'; + +/** The reviews section asks for its own data. These tests are about the rest of the page, so it gets no reviews. */ +const noReviews = (): MockLink.MockedResponse => ({ + request: { query: WINE_REVIEWS_QUERY, variables: { id: '100062', userId: USER_ID } }, + result: { + data: { + wine: { + __typename: 'Wine', + id: '100062', + studentRating: { __typename: 'StudentRating', average: null, count: 0 }, + reviews: [], + }, + myReview: null, + }, + }, +}); + function renderPage( mocks: MockLink.MockedResponse[], entry: string | { pathname: string; state: unknown } = '/vin/100062', ) { + window.localStorage.setItem(USER_ID_KEY, USER_ID); const user = userEvent.setup(); const result = render( - + } /> diff --git a/frontend/src/features/wine/WineView.tsx b/frontend/src/features/wine/WineView.tsx index a087a8d..3e0b806 100644 --- a/frontend/src/features/wine/WineView.tsx +++ b/frontend/src/features/wine/WineView.tsx @@ -11,6 +11,7 @@ import { buildSearchUrl } from '../../lib/searchParams'; import type { WineDetails } from '../../lib/types'; import { WINE_TYPES, wineTypeToken } from '../../lib/wineTypes'; import type { WineResult } from './api/useWine'; +import { StudentReviews } from './components/StudentReviews'; import styles from './WineView.module.css'; type WineViewProps = WineResult & { notFound: boolean }; @@ -142,6 +143,8 @@ function WineDetailsView({ wine }: { wine: WineDetails }) { )} + +

    ); } diff --git a/frontend/src/features/wine/api/reviewQueries.ts b/frontend/src/features/wine/api/reviewQueries.ts new file mode 100644 index 0000000..04c1a65 --- /dev/null +++ b/frontend/src/features/wine/api/reviewQueries.ts @@ -0,0 +1,60 @@ +import { gql } from '@apollo/client'; + +/** A student review as the API returns it. The author is a display name such as «Student #12». */ +export interface ApiReview { + id: string; + rating: number; + comment: string | null; + author: string; + updatedAt: string; +} + +export interface WineReviewsData { + wine: { + id: string; + studentRating: { average: number | null; count: number }; + reviews: ApiReview[]; + } | null; + myReview: Pick | null; +} + +/** The student part of the wine page, and the user's own review, in one request. */ +export const WINE_REVIEWS_QUERY = gql` + query WineReviews($id: ID!, $userId: ID!) { + wine(id: $id) { + id + studentRating { + average + count + } + reviews(first: 10) { + id + rating + comment + author + updatedAt + } + } + myReview(wineId: $id, userId: $userId) { + id + rating + comment + } + } +`; + +export const SAVE_REVIEW_MUTATION = gql` + mutation SaveReview($input: ReviewInput!) { + saveReview(input: $input) { + id + rating + comment + } + } +`; + +export const DELETE_REVIEW_MUTATION = gql` + mutation DeleteReview($wineId: ID!, $userId: ID!) { + deleteReview(wineId: $wineId, userId: $userId) + } +`; diff --git a/frontend/src/features/wine/api/useWineReviews.ts b/frontend/src/features/wine/api/useWineReviews.ts new file mode 100644 index 0000000..2d97ee3 --- /dev/null +++ b/frontend/src/features/wine/api/useWineReviews.ts @@ -0,0 +1,91 @@ +import { useMutation, useQuery } from '@apollo/client/react'; +import { useUserId } from '../../../hooks/useUserId'; +import type { RatingSummary } from '../../../lib/types'; +import { + DELETE_REVIEW_MUTATION, + SAVE_REVIEW_MUTATION, + WINE_REVIEWS_QUERY, + type ApiReview, + type WineReviewsData, +} from './reviewQueries'; + +export interface ReviewDraft { + rating: number; + comment: string; +} + +export interface WineReviewsResult { + students: RatingSummary | null; + reviews: ApiReview[]; + myReview: WineReviewsData['myReview']; + loading: boolean; + error: Error | undefined; + refetch: () => void; + /** Returns true when the review was saved. */ + save: (draft: ReviewDraft) => Promise; + /** Returns true when the review was deleted. */ + remove: () => Promise; + saving: boolean; +} + +/** The student reviews of one wine, and functions to save or delete the user's own review. */ +export function useWineReviews(wineId: string): WineReviewsResult { + const userId = useUserId(); + const { data, loading, error, refetch } = useQuery(WINE_REVIEWS_QUERY, { + variables: { id: wineId, userId }, + }); + + // After a change: fetch this wine's reviews again, and remove «Nylig dømt» from the cache, + // so the landing page asks for the new list the next time it is shown. + const afterChange = { + refetchQueries: ['WineReviews'], + awaitRefetchQueries: true, + }; + + const [saveReview, saveState] = useMutation(SAVE_REVIEW_MUTATION, { + ...afterChange, + update(cache) { + cache.evict({ fieldName: 'recentReviews' }); + }, + }); + + const [deleteReview, deleteState] = useMutation(DELETE_REVIEW_MUTATION, { + ...afterChange, + update(cache) { + cache.evict({ fieldName: 'recentReviews' }); + }, + }); + + async function save({ rating, comment }: ReviewDraft) { + try { + await saveReview({ + variables: { input: { wineId, userId, rating, comment: comment.trim() || null } }, + }); + return true; + } catch { + return false; // The form shows its own message in Norwegian. + } + } + + async function remove() { + try { + await deleteReview({ variables: { wineId, userId } }); + return true; + } catch { + return false; + } + } + + return { + students: data?.wine?.studentRating ?? null, + reviews: data?.wine?.reviews ?? [], + myReview: data?.myReview ?? null, + loading, + error, + // A failed retry already shows up in `error`, so the rejected promise needs no handling. + refetch: () => void refetch().catch(() => undefined), + save, + remove, + saving: saveState.loading || deleteState.loading, + }; +} diff --git a/frontend/src/features/wine/components/ReviewForm.module.css b/frontend/src/features/wine/components/ReviewForm.module.css new file mode 100644 index 0000000..1e36755 --- /dev/null +++ b/frontend/src/features/wine/components/ReviewForm.module.css @@ -0,0 +1,104 @@ +.form { + display: grid; + gap: var(--space-4); +} + +.legend { + margin-bottom: var(--space-2); + font-weight: 700; +} + +.stars { + margin: 0; + padding: 0; + border: 0; +} + +.option:hover { + background: var(--color-surface-muted); +} + +.options { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +/* The radio button is invisible but still focusable and readable. The die face is what you see. */ +.option { + position: relative; + display: grid; + place-items: center; + min-width: var(--tap-target); + min-height: var(--tap-target); + padding: var(--space-1); + border: 2px solid transparent; + border-radius: var(--radius-lg); + cursor: pointer; +} + +.radio { + position: absolute; + inset: 0; + margin: 0; + opacity: 0; + cursor: pointer; +} + +.option:has(.radio:focus-visible) { + outline: 3px solid var(--color-focus); + outline-offset: 2px; +} + +.field { + display: grid; + gap: var(--space-1); +} + +.comment { + width: 100%; + padding: var(--space-2); + border: 1px solid var(--color-border); + border-radius: var(--radius-lg); + font: inherit; + color: inherit; + background: transparent; + resize: vertical; +} + +.count { + font-size: var(--text-sm); + color: var(--color-text-muted); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-2); +} + +.primary, +.secondary { + min-height: var(--tap-target); + padding: 0 var(--space-5); + border: 2px solid var(--color-link); + border-radius: var(--radius-pill); + font-weight: 700; + cursor: pointer; +} + +.primary { + background: var(--color-link); + color: var(--color-surface, #fff); +} + +.secondary { + background: transparent; + color: var(--color-text); +} + +.primary:disabled, +.secondary:disabled { + opacity: 0.6; + cursor: progress; +} diff --git a/frontend/src/features/wine/components/ReviewForm.test.tsx b/frontend/src/features/wine/components/ReviewForm.test.tsx new file mode 100644 index 0000000..421e7a0 --- /dev/null +++ b/frontend/src/features/wine/components/ReviewForm.test.tsx @@ -0,0 +1,74 @@ +import { describe, expect, it, vi } from 'vitest'; +import { render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import type { ComponentProps } from 'react'; +import { axe } from 'vitest-axe'; +import { MAX_COMMENT_LENGTH, ReviewForm } from './ReviewForm'; + +function renderForm(props: Partial> = {}) { + const onSave = vi.fn(); + const onDelete = vi.fn(); + const user = userEvent.setup(); + const result = render( + , + ); + return { user, onSave, onDelete, ...result }; +} + +const commentField = () => screen.getByLabelText('Kommentar (valgfritt)'); + +describe('ReviewForm', () => { + it('has five stars as radio buttons in one group', () => { + renderForm(); + const group = screen.getByRole('group', { name: 'Gi din dom' }); + expect(within(group).getAllByRole('radio')).toHaveLength(5); + expect(screen.getByRole('radio', { name: '4 av 5 stjerner' })).toBeInTheDocument(); + }); + + it('saves the chosen stars and the comment', async () => { + const { user, onSave } = renderForm(); + await user.click(screen.getByRole('radio', { name: '4 av 5 stjerner' })); + await user.type(commentField(), 'Fin til pizza'); + await user.click(screen.getByRole('button', { name: 'Lagre dommen' })); + expect(onSave).toHaveBeenCalledWith({ rating: 4, comment: 'Fin til pizza' }); + }); + + it('does not save without stars', async () => { + const { user, onSave } = renderForm(); + await user.click(screen.getByRole('button', { name: 'Lagre dommen' })); + expect(onSave).not.toHaveBeenCalled(); + }); + + it('shows the saved review and can delete it', async () => { + const { user, onDelete } = renderForm({ myReview: { rating: 2, comment: 'For søt' } }); + expect(screen.getByRole('radio', { name: '2 av 5 stjerner' })).toBeChecked(); + expect(commentField()).toHaveValue('For søt'); + expect(screen.getByRole('button', { name: 'Oppdater dommen' })).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Slett dommen' })); + expect(onDelete).toHaveBeenCalledOnce(); + }); + + it('has no delete button before the user has saved a review', () => { + renderForm(); + expect(screen.queryByRole('button', { name: 'Slett dommen' })).not.toBeInTheDocument(); + }); + + it('counts the characters and has the same limit as the API', async () => { + const { user } = renderForm(); + expect(commentField()).toHaveAttribute('maxlength', String(MAX_COMMENT_LENGTH)); + await user.type(commentField(), 'Hei'); + expect(screen.getByText(`3 av ${MAX_COMMENT_LENGTH} tegn`)).toBeInTheDocument(); + }); + + it('disables the buttons while saving', () => { + renderForm({ myReview: { rating: 3, comment: null }, saving: true }); + expect(screen.getByRole('button', { name: 'Oppdater dommen' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Slett dommen' })).toBeDisabled(); + }); + + it('has no axe violations', async () => { + const { container } = renderForm({ myReview: { rating: 4, comment: 'God' } }); + expect(await axe(container)).toHaveNoViolations(); + }); +}); diff --git a/frontend/src/features/wine/components/ReviewForm.tsx b/frontend/src/features/wine/components/ReviewForm.tsx new file mode 100644 index 0000000..19e7882 --- /dev/null +++ b/frontend/src/features/wine/components/ReviewForm.tsx @@ -0,0 +1,81 @@ +import { useId, useState, type FormEvent } from 'react'; +import { StarIcon } from '../../../components/ui/Stars'; +import type { ReviewDraft } from '../api/useWineReviews'; +import styles from './ReviewForm.module.css'; + +export const MAX_COMMENT_LENGTH = 500; +const STARS = [1, 2, 3, 4, 5]; + +interface ReviewFormProps { + /** The user's saved review, or null if they have not reviewed the wine. */ + myReview: { rating: number; comment: string | null } | null; + saving: boolean; + onSave: (draft: ReviewDraft) => void; + onDelete: () => void; +} + +/** Stars and an optional comment. The stars are radio buttons, so they work with keyboard and screen readers. */ +export function ReviewForm({ myReview, saving, onSave, onDelete }: ReviewFormProps) { + const [rating, setRating] = useState(myReview?.rating ?? null); + const [comment, setComment] = useState(myReview?.comment ?? ''); + const commentId = useId(); + const countId = useId(); + + function handleSubmit(event: FormEvent) { + event.preventDefault(); + if (rating !== null) onSave({ rating, comment }); + } + + return ( +
    +
    + {myReview ? 'Din dom' : 'Gi din dom'} +
    + {STARS.map((value) => ( + + ))} +
    +
    + +
    + +