diff --git a/README.md b/README.md index 9824fe7..ba86c53 100644 --- a/README.md +++ b/README.md @@ -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 1 to 5 stars. +Students can search, filter and sort a catalogue of wines. Each wine shows one average of all ratings, from the X-Wines dataset and from other students, and how many gave each score. Students give their own verdict as 0.5 to 5 stars, in half 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. @@ -53,7 +53,7 @@ Submission 3 should be the first complete prototype, with search, browsing, sort | 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, 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 | +| Student reviews (stored in the database) | Done | 0.5–5 stars and an optional comment, saved and shown at once on the wine page. They count in the shared average | | Larger dataset on the VM | Done | Slim version: 1 007 wines and 150 000 ratings | | Continuous integration (CI) | Not yet started | | @@ -106,7 +106,8 @@ This section describes what users can do. "Backend" means the API supports the f | 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 | 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 | +| Student reviews | Done | Done | 0.5–5 stars in half stars and an optional comment, stored in PostgreSQL. Hover the left half of a star for half a star, or use the arrow keys. The page updates at once without a reload. One review per student per wine | +| Shared average and distribution | Done | Done | Student reviews count in the average together with X-Wines, also when sorting and filtering. The wine page shows how many gave each score | | Wishlist ("Vil prøve") | Planned | Done, stored in the browser | Moves to the backend when users and reviews are in place | | User | Done (Anonymous ID) | Done | An anonymous ID stored in browser until we have login (#29) | diff --git a/frontend/e2e/wine.spec.ts b/frontend/e2e/wine.spec.ts index 204616f..98b7dfc 100644 --- a/frontend/e2e/wine.spec.ts +++ b/frontend/e2e/wine.spec.ts @@ -53,6 +53,7 @@ async function stubApi(page: Page) { __typename: 'Wine', id: wine.id, studentRating: { __typename: 'StudentRating', average: null, count: 0 }, + ratingDistribution: [], reviews: [], }, myReview: null, diff --git a/frontend/src/components/ui/Stars.module.css b/frontend/src/components/ui/Stars.module.css index be92e20..de75f5a 100644 --- a/frontend/src/components/ui/Stars.module.css +++ b/frontend/src/components/ui/Stars.module.css @@ -8,25 +8,28 @@ gap: 2px; } -.filled, -.empty { +.star { flex-shrink: 0; - stroke-width: 1.5; - stroke-linejoin: round; } -.filled { - fill: var(--color-brand); - stroke: var(--color-brand); +.outline, +.fill { + stroke-width: 1.5; + stroke-linejoin: round; } -.empty { +.outline { fill: none; stroke: var(--color-text-muted); } +.fill { + fill: var(--color-brand); + stroke: var(--color-brand); +} + @media (prefers-color-scheme: dark) { - .filled { + .fill { fill: var(--cork-300); stroke: var(--cork-300); } diff --git a/frontend/src/components/ui/Stars.test.tsx b/frontend/src/components/ui/Stars.test.tsx new file mode 100644 index 0000000..5e5d6ad --- /dev/null +++ b/frontend/src/components/ui/Stars.test.tsx @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { formatStars, starFill } from '../../lib/stars'; +import { Stars } from './Stars'; + +const ALL_STARS = [1, 2, 3, 4, 5]; + +describe('starFill', () => { + it('fills whole stars, half a star, and leaves the rest empty', () => { + expect(ALL_STARS.map((star) => starFill(star, 3.5))).toEqual([ + 'full', + 'full', + 'full', + 'half', + 'empty', + ]); + }); + + it('leaves every star empty without a rating', () => { + expect(ALL_STARS.map((star) => starFill(star, null))).toEqual(Array(5).fill('empty')); + }); +}); + +describe('formatStars', () => { + it('shows a decimal only when it is needed', () => { + expect(formatStars(3.5)).toBe('3,5'); + expect(formatStars(4)).toBe('4'); + }); +}); + +describe('Stars', () => { + it('rounds to the nearest half star and gives screen readers the value as text', () => { + render(); + expect(screen.getByText('4 av 5 stjerner')).toBeInTheDocument(); + }); + + it('draws half a star', () => { + const { container } = render(); + expect(screen.getByText('2,5 av 5 stjerner')).toBeInTheDocument(); + expect(container.querySelectorAll('clipPath')).toHaveLength(1); + }); +}); diff --git a/frontend/src/components/ui/Stars.tsx b/frontend/src/components/ui/Stars.tsx index b860b28..a396dfa 100644 --- a/frontend/src/components/ui/Stars.tsx +++ b/frontend/src/components/ui/Stars.tsx @@ -1,41 +1,60 @@ +import { useId } from 'react'; +import { formatStars, starFill, type StarFill } from '../../lib/stars'; 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 }) { +export function StarIcon({ fill, size = 20 }: { fill: StarFill; size?: number }) { + // The id must be unique on the page and valid in url(#...), so special characters are removed. + const clipId = `half-star-${useId().replace(/[^a-zA-Z0-9_-]/g, '')}`; + return ( ); } interface StarsProps { - /** 1–5. Rounded to whole stars. */ + /** 0.5–5. Rounded to the nearest half star. */ value: number; size?: number; } -/** A rating as five stars, with the text «4 av 5 stjerner» for screen readers. */ +/** A rating as five stars, with the text «3,5 av 5 stjerner» for screen readers. */ export function Stars({ value, size = 20 }: StarsProps) { - const filled = Math.min(5, Math.max(0, Math.round(value))); + const rounded = Math.min(5, Math.max(0, Math.round(value * 2) / 2)); return ( - {filled} av 5 stjerner + {formatStars(rounded)} av 5 stjerner ); } diff --git a/frontend/src/features/wine/WinePage.test.tsx b/frontend/src/features/wine/WinePage.test.tsx index 05c8798..3b13fbf 100644 --- a/frontend/src/features/wine/WinePage.test.tsx +++ b/frontend/src/features/wine/WinePage.test.tsx @@ -58,6 +58,7 @@ const noReviews = (): MockLink.MockedResponse => ({ __typename: 'Wine', id: '100062', studentRating: { __typename: 'StudentRating', average: null, count: 0 }, + ratingDistribution: [], reviews: [], }, myReview: null, diff --git a/frontend/src/features/wine/api/reviewQueries.ts b/frontend/src/features/wine/api/reviewQueries.ts index 04c1a65..33d770b 100644 --- a/frontend/src/features/wine/api/reviewQueries.ts +++ b/frontend/src/features/wine/api/reviewQueries.ts @@ -9,16 +9,23 @@ export interface ApiReview { updatedAt: string; } +/** How many gave one score (0.5–5), from X-Wines and students together. */ +export interface RatingCount { + rating: number; + count: number; +} + export interface WineReviewsData { wine: { id: string; studentRating: { average: number | null; count: number }; + ratingDistribution: RatingCount[]; reviews: ApiReview[]; } | null; myReview: Pick | null; } -/** The student part of the wine page, and the user's own review, in one request. */ +/** The reviews 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) { @@ -27,6 +34,10 @@ export const WINE_REVIEWS_QUERY = gql` average count } + ratingDistribution { + rating + count + } reviews(first: 10) { id rating diff --git a/frontend/src/features/wine/api/useWineReviews.ts b/frontend/src/features/wine/api/useWineReviews.ts index 2d97ee3..24a5da6 100644 --- a/frontend/src/features/wine/api/useWineReviews.ts +++ b/frontend/src/features/wine/api/useWineReviews.ts @@ -6,6 +6,7 @@ import { SAVE_REVIEW_MUTATION, WINE_REVIEWS_QUERY, type ApiReview, + type RatingCount, type WineReviewsData, } from './reviewQueries'; @@ -17,6 +18,7 @@ export interface ReviewDraft { export interface WineReviewsResult { students: RatingSummary | null; reviews: ApiReview[]; + distribution: RatingCount[]; myReview: WineReviewsData['myReview']; loading: boolean; error: Error | undefined; @@ -38,7 +40,7 @@ export function useWineReviews(wineId: string): WineReviewsResult { // 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'], + refetchQueries: ['WineReviews', 'Wine'], awaitRefetchQueries: true, }; @@ -79,6 +81,7 @@ export function useWineReviews(wineId: string): WineReviewsResult { return { students: data?.wine?.studentRating ?? null, reviews: data?.wine?.reviews ?? [], + distribution: data?.wine?.ratingDistribution ?? [], myReview: data?.myReview ?? null, loading, error, diff --git a/frontend/src/features/wine/components/RatingDistribution.module.css b/frontend/src/features/wine/components/RatingDistribution.module.css new file mode 100644 index 0000000..ddb49ff --- /dev/null +++ b/frontend/src/features/wine/components/RatingDistribution.module.css @@ -0,0 +1,52 @@ +.distribution { + display: grid; + gap: var(--space-2); +} + +.title { + font-size: var(--text-lg); +} + +.note { + font-size: var(--text-sm); + color: var(--color-text-muted); +} + +.rows { + display: grid; + gap: var(--space-1); + margin: 0; + padding: 0; + list-style: none; +} + +.row { + display: grid; + grid-template-columns: 6rem 1fr 3rem; + align-items: center; + gap: var(--space-2); +} + +.bar { + height: 0.75rem; + border-radius: var(--radius-pill); + background: var(--color-surface-muted); + overflow: hidden; +} + +.fill { + display: block; + height: 100%; + background: var(--color-brand); +} + +.count { + text-align: right; + font-variant-numeric: tabular-nums; +} + +@media (prefers-color-scheme: dark) { + .fill { + background: var(--cork-300); + } +} diff --git a/frontend/src/features/wine/components/RatingDistribution.test.tsx b/frontend/src/features/wine/components/RatingDistribution.test.tsx new file mode 100644 index 0000000..b489e5b --- /dev/null +++ b/frontend/src/features/wine/components/RatingDistribution.test.tsx @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { axe } from 'vitest-axe'; +import { groupByStars } from '../../../lib/stars'; +import { RatingDistribution } from './RatingDistribution'; +describe('groupByStars', () => { + it('counts half stars with the star above, from five stars to one', () => { + expect( + groupByStars([ + { rating: 5, count: 7 }, + { rating: 4.5, count: 1 }, + { rating: 3.5, count: 6 }, + { rating: 0.5, count: 2 }, + ]), + ).toEqual([ + { stars: 5, count: 8 }, + { stars: 4, count: 6 }, + { stars: 3, count: 0 }, + { stars: 2, count: 0 }, + { stars: 1, count: 2 }, + ]); + }); +}); + +describe('RatingDistribution', () => { + it('shows every row with the number as text', () => { + render( + , + ); + const rows = screen.getAllByRole('listitem'); + expect(rows).toHaveLength(5); + expect(rows[0]).toHaveTextContent(/5 stjerner\s*9 vurderinger/); + expect(rows[4]).toHaveTextContent(/1 stjerne\s*1 vurdering/); + }); + + it('shows nothing when nobody has rated the wine', () => { + const { container } = render(); + expect(container).toBeEmptyDOMElement(); + }); + + it('has no axe violations', async () => { + const { container } = render(); + expect(await axe(container)).toHaveNoViolations(); + }); +}); diff --git a/frontend/src/features/wine/components/RatingDistribution.tsx b/frontend/src/features/wine/components/RatingDistribution.tsx new file mode 100644 index 0000000..7783957 --- /dev/null +++ b/frontend/src/features/wine/components/RatingDistribution.tsx @@ -0,0 +1,34 @@ +import { pluralize } from '../../../lib/format'; +import { groupByStars } from '../../../lib/stars'; +import type { RatingCount } from '../api/reviewQueries'; +import styles from './RatingDistribution.module.css'; + +/** How many gave each score, as a list with bars. The bars are only decoration; the numbers are text. */ +export function RatingDistribution({ distribution }: { distribution: RatingCount[] }) { + const rows = groupByStars(distribution); + const highest = Math.max(...rows.map((row) => row.count)); + if (highest === 0) return null; + + return ( +
+

Alle vurderinger

+

+ Fra X-Wines og studenter. Halve stjerner telles med stjernen over. +

+
    + {rows.map(({ stars, count }) => ( +
  • + {pluralize(stars, 'stjerne', 'stjerner')} +
  • + ))} +
+
+ ); +} diff --git a/frontend/src/features/wine/components/ReviewForm.module.css b/frontend/src/features/wine/components/ReviewForm.module.css index 1e36755..11b11ab 100644 --- a/frontend/src/features/wine/components/ReviewForm.module.css +++ b/frontend/src/features/wine/components/ReviewForm.module.css @@ -3,40 +3,50 @@ 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); +.legend { + margin-bottom: var(--space-2); + font-weight: 700; } .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 { +/* One star, 48 px wide, so each half is at least 24 × 24 px to click (WCAG 2.5.8). */ +.slot { 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; + width: 48px; + height: 48px; border-radius: var(--radius-lg); +} + +.left, +.right { + position: absolute; + top: 0; + bottom: 0; + width: 50%; cursor: pointer; } +.left { + left: 0; +} + +.right { + right: 0; +} + +/* The radio button is invisible, but still focusable and readable. */ .radio { position: absolute; inset: 0; @@ -45,11 +55,17 @@ cursor: pointer; } -.option:has(.radio:focus-visible) { +.slot:has(.radio:focus-visible) { outline: 3px solid var(--color-focus); outline-offset: 2px; } +.chosen { + margin-top: var(--space-1); + font-size: var(--text-sm); + color: var(--color-text-muted); +} + .field { display: grid; gap: var(--space-1); diff --git a/frontend/src/features/wine/components/ReviewForm.test.tsx b/frontend/src/features/wine/components/ReviewForm.test.tsx index 421e7a0..8b6b91c 100644 --- a/frontend/src/features/wine/components/ReviewForm.test.tsx +++ b/frontend/src/features/wine/components/ReviewForm.test.tsx @@ -18,11 +18,27 @@ function renderForm(props: Partial> = {}) { const commentField = () => screen.getByLabelText('Kommentar (valgfritt)'); describe('ReviewForm', () => { - it('has five stars as radio buttons in one group', () => { + it('has ten choices from half a star to five stars 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(); + const radios = within(group).getAllByRole('radio'); + expect(radios).toHaveLength(10); + expect(radios[0]).toHaveAccessibleName('0,5 av 5 stjerner'); + expect(radios[9]).toHaveAccessibleName('5 av 5 stjerner'); + }); + + it('saves half stars', async () => { + const { user, onSave } = renderForm(); + await user.click(screen.getByRole('radio', { name: '3,5 av 5 stjerner' })); + await user.click(screen.getByRole('button', { name: 'Lagre dommen' })); + expect(onSave).toHaveBeenCalledWith({ rating: 3.5, comment: '' }); + }); + + it('shows the chosen score as text', async () => { + const { user } = renderForm(); + expect(screen.getByText('Velg antall stjerner')).toBeInTheDocument(); + await user.click(screen.getByRole('radio', { name: '2,5 av 5 stjerner' })); + expect(screen.getByText('2,5 av 5')).toBeInTheDocument(); }); it('saves the chosen stars and the comment', async () => { diff --git a/frontend/src/features/wine/components/ReviewForm.tsx b/frontend/src/features/wine/components/ReviewForm.tsx index 19e7882..3290b1d 100644 --- a/frontend/src/features/wine/components/ReviewForm.tsx +++ b/frontend/src/features/wine/components/ReviewForm.tsx @@ -1,5 +1,6 @@ import { useId, useState, type FormEvent } from 'react'; import { StarIcon } from '../../../components/ui/Stars'; +import { formatStars, starFill } from '../../../lib/stars'; import type { ReviewDraft } from '../api/useWineReviews'; import styles from './ReviewForm.module.css'; @@ -14,13 +15,21 @@ interface ReviewFormProps { onDelete: () => void; } -/** Stars and an optional comment. The stars are radio buttons, so they work with keyboard and screen readers. */ +/** + * Half stars and an optional comment. Each star has two invisible radio buttons: + * the left half gives half a star, the right half a whole star. The arrow keys move + * through all ten values, and screen readers read «3,5 av 5 stjerner». + */ export function ReviewForm({ myReview, saving, onSave, onDelete }: ReviewFormProps) { const [rating, setRating] = useState(myReview?.rating ?? null); + const [hovered, setHovered] = useState(null); const [comment, setComment] = useState(myReview?.comment ?? ''); const commentId = useId(); const countId = useId(); + // While the mouse is over the stars, they show what a click would give. + const shown = hovered ?? rating; + function handleSubmit(event: FormEvent) { event.preventDefault(); if (rating !== null) onSave({ rating, comment }); @@ -30,24 +39,34 @@ export function ReviewForm({ myReview, saving, onSave, onDelete }: ReviewFormPro
{myReview ? 'Din dom' : 'Gi din dom'} -
- {STARS.map((value) => ( - +
setHovered(null)}> + {STARS.map((star) => ( + + + {[star - 0.5, star].map((value) => ( + + ))} + ))}
+
diff --git a/frontend/src/features/wine/components/StudentReviews.module.css b/frontend/src/features/wine/components/StudentReviews.module.css index 42a141f..760a067 100644 --- a/frontend/src/features/wine/components/StudentReviews.module.css +++ b/frontend/src/features/wine/components/StudentReviews.module.css @@ -48,3 +48,7 @@ .empty { color: var(--color-text-muted); } + +.subtitle { + font-size: var(--text-lg); +} diff --git a/frontend/src/features/wine/components/StudentReviews.tsx b/frontend/src/features/wine/components/StudentReviews.tsx index 00363ad..f6a59b9 100644 --- a/frontend/src/features/wine/components/StudentReviews.tsx +++ b/frontend/src/features/wine/components/StudentReviews.tsx @@ -4,6 +4,7 @@ import { ErrorNotice } from '../../../components/ui/ErrorNotice'; import { Skeleton } from '../../../components/ui/Skeleton'; import { formatRatingSummary, formatRelativeTime } from '../../../lib/format'; import { useWineReviews, type ReviewDraft } from '../api/useWineReviews'; +import { RatingDistribution } from './RatingDistribution'; import { ReviewForm } from './ReviewForm'; import styles from './StudentReviews.module.css'; @@ -13,10 +14,20 @@ interface StudentReviewsProps { now?: Date; } -/** The students' average, the user's own review and the newest reviews of one wine. */ +/** All ratings of one wine, the students' average, the user's own review and the newest reviews. */ export function StudentReviews({ wineId, now }: StudentReviewsProps) { - const { students, reviews, myReview, loading, error, refetch, save, remove, saving } = - useWineReviews(wineId); + const { + students, + reviews, + distribution, + myReview, + loading, + error, + refetch, + save, + remove, + saving, + } = useWineReviews(wineId); const [message, setMessage] = useState(''); async function handleSave(draft: ReviewDraft) { @@ -33,7 +44,7 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) { return (
-

Studentenes dommer

+

Vurderinger

{loading && } @@ -41,6 +52,9 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) { {!loading && !error && ( <> + +

Studentenes dommer

+

{formatRatingSummary(students ?? { average: null, count: 0 }, { singular: 'dom', diff --git a/frontend/src/lib/stars.ts b/frontend/src/lib/stars.ts new file mode 100644 index 0000000..40da915 --- /dev/null +++ b/frontend/src/lib/stars.ts @@ -0,0 +1,32 @@ +// Helpers for ratings in half stars from 0.5 to 5. + +export type StarFill = 'full' | 'half' | 'empty'; + +/** How much of star number `star` (1–5) is filled for a rating. */ +export function starFill(star: number, rating: number | null): StarFill { + if (rating === null || rating < star - 0.5) return 'empty'; + return rating >= star ? 'full' : 'half'; +} + +/** «3,5» or «4»: one decimal only when needed. */ +export function formatStars(rating: number): string { + return new Intl.NumberFormat('nb-NO', { maximumFractionDigits: 1 }).format(rating); +} + +export interface StarRow { + stars: number; + count: number; +} + +/** + * Groups scores into five rows, one per whole star, highest first. + * A half star counts with the star above it: 3.5 counts as 4, and 0.5 as 1. + */ +export function groupByStars(distribution: { rating: number; count: number }[]): StarRow[] { + const rows = [5, 4, 3, 2, 1].map((stars) => ({ stars, count: 0 })); + for (const { rating, count } of distribution) { + const stars = Math.min(5, Math.max(1, Math.ceil(rating))); + rows[5 - stars].count += count; + } + return rows; +}