From 2c1258587085c9ae9e5a1d5ca403a091305e6534 Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Thu, 12 Nov 2026 11:59:06 +0100 Subject: [PATCH 1/9] feat(reviews): add an anonymous user ID for reviews (#49) --- backend/src/schema.ts | 2 +- frontend/src/hooks/useUserId.test.ts | 49 ++++++++++++++++++++++++++++ frontend/src/hooks/useUserId.ts | 48 +++++++++++++++++++++++++++ 3 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 frontend/src/hooks/useUserId.test.ts create mode 100644 frontend/src/hooks/useUserId.ts 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/frontend/src/hooks/useUserId.test.ts b/frontend/src/hooks/useUserId.test.ts new file mode 100644 index 0000000..3b6ed7d --- /dev/null +++ b/frontend/src/hooks/useUserId.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createId, getUserId, USER_ID_KEY } from './useUserId'; + +// A version 4 UUID: the third group starts with 4, the fourth with 8, 9, a or b. +const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + +afterEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('createId', () => { + it('creates a version 4 UUID', () => { + expect(createId()).toMatch(UUID_V4); + }); + + it('works without crypto.randomUUID, as on the VM over plain HTTP', () => { + const realCrypto = globalThis.crypto; + vi.stubGlobal('crypto', { getRandomValues: realCrypto.getRandomValues.bind(realCrypto) }); + + expect(createId()).toMatch(UUID_V4); + expect(createId()).not.toBe(createId()); + }); +}); + +describe('getUserId', () => { + it('creates an ID the first time and keeps it', () => { + const id = getUserId(); + expect(id).toMatch(UUID_V4); + expect(getUserId()).toBe(id); + expect(window.localStorage.getItem(USER_ID_KEY)).toBe(id); + }); + + it('replaces a saved value that is not a UUID', () => { + window.localStorage.setItem(USER_ID_KEY, 'not-an-id'); + expect(getUserId()).toMatch(UUID_V4); + }); + + it('keeps the same ID for the visit when localStorage is unavailable', () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new Error('Private mode'); + }); + + const id = getUserId(); + expect(id).toMatch(UUID_V4); + expect(getUserId()).toBe(id); + }); +}); \ No newline at end of file diff --git a/frontend/src/hooks/useUserId.ts b/frontend/src/hooks/useUserId.ts new file mode 100644 index 0000000..ee46681 --- /dev/null +++ b/frontend/src/hooks/useUserId.ts @@ -0,0 +1,48 @@ +import { useState } from 'react'; + +/* + * Anonymous ID for student reviews, kept in the browser until we have login (#29). + * It works like a password: whoever knows it can change the user's reviews. + * The API never sends it back, and the interface never shows it. + */ +export const USER_ID_KEY = 'kk:user-id'; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** A random version 4 UUID. */ +export function createId(): string { + if (typeof crypto.randomUUID === 'function') return crypto.randomUUID(); + + // randomUUID only exists on HTTPS and localhost. The VM uses plain HTTP, + // so there we build the UUID from random bytes ourselves. + const bytes = crypto.getRandomValues(new Uint8Array(16)); + bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4 + bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant + const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +// Used when localStorage is unavailable, so the ID at least lasts for this visit. +let sessionId: string | undefined; + +/** Reads the saved ID, or creates and saves a new one. */ +export function getUserId(): string { + try { + const saved = window.localStorage.getItem(USER_ID_KEY); + if (saved && UUID.test(saved)) return saved; + + const id = createId(); + window.localStorage.setItem(USER_ID_KEY, id); + return id; + } catch { + // Private mode or full storage. + sessionId ??= createId(); + return sessionId; + } +} + +/** The same ID for the whole visit, read once when the component mounts. */ +export function useUserId(): string { + const [id] = useState(getUserId); + return id; +} \ No newline at end of file From f553ff61b1b57b8df01607a7b28c8cc2d8bc46ea Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Thu, 12 Nov 2026 12:08:48 +0100 Subject: [PATCH 2/9] feat(reviews): add queries and a hook for wine reviews (#49) --- .../src/features/wine/api/reviewQueries.ts | 60 ++++++++++++ .../src/features/wine/api/useWineReviews.ts | 91 +++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 frontend/src/features/wine/api/reviewQueries.ts create mode 100644 frontend/src/features/wine/api/useWineReviews.ts diff --git a/frontend/src/features/wine/api/reviewQueries.ts b/frontend/src/features/wine/api/reviewQueries.ts new file mode 100644 index 0000000..c0c594c --- /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) + } +`; \ No newline at end of file diff --git a/frontend/src/features/wine/api/useWineReviews.ts b/frontend/src/features/wine/api/useWineReviews.ts new file mode 100644 index 0000000..fc200a0 --- /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, + }; +} \ No newline at end of file From dce431e2d99b3c747c9d8748b48e11ee1996a795 Mon Sep 17 00:00:00 2001 From: SivertEikrem Date: Thu, 12 Nov 2026 12:31:56 +0100 Subject: [PATCH 3/9] feat(reviews): let students rate wines with stars on the wine page (#49) --- frontend/src/components/ui/Stars.module.css | 33 ++++++ frontend/src/components/ui/Stars.tsx | 41 +++++++ frontend/src/features/wine/WineView.tsx | 5 +- .../wine/components/ReviewForm.module.css | 104 ++++++++++++++++++ .../features/wine/components/ReviewForm.tsx | 81 ++++++++++++++ .../wine/components/StudentReviews.module.css | 50 +++++++++ .../wine/components/StudentReviews.tsx | 87 +++++++++++++++ 7 files changed, 400 insertions(+), 1 deletion(-) create mode 100644 frontend/src/components/ui/Stars.module.css create mode 100644 frontend/src/components/ui/Stars.tsx create mode 100644 frontend/src/features/wine/components/ReviewForm.module.css create mode 100644 frontend/src/features/wine/components/ReviewForm.tsx create mode 100644 frontend/src/features/wine/components/StudentReviews.module.css create mode 100644 frontend/src/features/wine/components/StudentReviews.tsx diff --git a/frontend/src/components/ui/Stars.module.css b/frontend/src/components/ui/Stars.module.css new file mode 100644 index 0000000..5827c19 --- /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); + } +} \ No newline at end of file diff --git a/frontend/src/components/ui/Stars.tsx b/frontend/src/components/ui/Stars.tsx new file mode 100644 index 0000000..78bfcf3 --- /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 + + ); +} \ No newline at end of file diff --git a/frontend/src/features/wine/WineView.tsx b/frontend/src/features/wine/WineView.tsx index a087a8d..ff71c47 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 }) { )} + + ); } @@ -153,4 +156,4 @@ function Fact({ term, children }: { term: string; children: ReactNode }) {
{children}
); -} +} \ No newline at end of file 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..666d47e --- /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; +} \ No newline at end of file diff --git a/frontend/src/features/wine/components/ReviewForm.tsx b/frontend/src/features/wine/components/ReviewForm.tsx new file mode 100644 index 0000000..f9bcb70 --- /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) => ( + + ))} +
+
+ +
+ +