diff --git a/client/src/api/albumDetail.test.ts b/client/src/api/albumDetail.test.ts index 673388c..108b54f 100644 --- a/client/src/api/albumDetail.test.ts +++ b/client/src/api/albumDetail.test.ts @@ -3,7 +3,14 @@ import { buildSchema, validate } from 'graphql'; import { expect, it } from 'vitest'; import { ALBUM_DETAIL } from './albumDetail.js'; +import { DELETE_REVIEW, UPSERT_REVIEW } from './reviews.js'; it('validates the album-detail operation against the repository schema', () => { expect(validate(buildSchema(schemaSource), ALBUM_DETAIL)).toEqual([]); }); + +it('validates review mutations against the repository schema', () => { + const schema = buildSchema(schemaSource); + expect(validate(schema, UPSERT_REVIEW)).toEqual([]); + expect(validate(schema, DELETE_REVIEW)).toEqual([]); +}); diff --git a/client/src/api/albumDetail.ts b/client/src/api/albumDetail.ts index addc6b6..693b704 100644 --- a/client/src/api/albumDetail.ts +++ b/client/src/api/albumDetail.ts @@ -29,6 +29,7 @@ export type AlbumDetail = { pageInfo: { hasNextPage: boolean; endCursor: string | null }; totalCount: number; }; + myReview: { id: string; rating: number; comment: string } | null; }; type AlbumDetailData = { album: AlbumDetail | null }; @@ -60,6 +61,11 @@ export const ALBUM_DETAIL: TypedDocumentNode & { @@ -55,7 +57,9 @@ export const cache = new InMemoryCache({ // ApolloClient coordinates requests and the cache for components under ApolloProvider. export const apolloClient = new ApolloClient({ cache, - // HttpLink sends GraphQL operations over HTTP, independently of the /project2/ asset base. - // TODO(#6): Verify the endpoint and any identity header against the real backend. - link: new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL || '/graphql' }), + // Every request carries the simulated identity. It is not authentication; + // the server uses it only to separate this browser's reviews and crate. + link: setContext((_, { headers }) => ({ + headers: { ...headers, 'X-User-Id': getUserId() }, + })).concat(new HttpLink({ uri: import.meta.env.VITE_GRAPHQL_URL || '/graphql' })), }); diff --git a/client/src/api/reviews.ts b/client/src/api/reviews.ts new file mode 100644 index 0000000..6782bff --- /dev/null +++ b/client/src/api/reviews.ts @@ -0,0 +1,44 @@ +import { gql } from '@apollo/client'; +import type { TypedDocumentNode } from '@apollo/client'; + +type ReviewPayload = { + review: { id: string; rating: number; comment: string }; + album: { id: string }; +}; + +type DeleteReviewPayload = { + deletedReviewId: string; + album: { id: string }; +}; + +export const UPSERT_REVIEW: TypedDocumentNode< + { upsertReview: ReviewPayload }, + { input: { albumId: string; rating: number; comment: string } } +> = gql` + mutation UpsertReview($input: UpsertReviewInput!) { + upsertReview(input: $input) { + review { + id + rating + comment + } + album { + id + } + } + } +`; + +export const DELETE_REVIEW: TypedDocumentNode< + { deleteReview: DeleteReviewPayload }, + { id: string } +> = gql` + mutation DeleteReview($id: ID!) { + deleteReview(id: $id) { + deletedReviewId + album { + id + } + } + } +`; diff --git a/client/src/api/userIdentity.test.ts b/client/src/api/userIdentity.test.ts new file mode 100644 index 0000000..0fcd1e3 --- /dev/null +++ b/client/src/api/userIdentity.test.ts @@ -0,0 +1,47 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { getUserId, USER_ID_STORAGE_KEY } from './userIdentity.js'; + +const generatedId = '550e8400-e29b-41d4-a716-446655440000'; + +beforeEach(() => { + window.localStorage.clear(); + vi.spyOn(crypto, 'randomUUID').mockReturnValue(generatedId); +}); + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('getUserId', () => { + it('creates and persists a UUID the first time', () => { + expect(getUserId()).toBe(generatedId); + expect(window.localStorage.getItem(USER_ID_STORAGE_KEY)).toBe(generatedId); + }); + + it('reuses a stored UUID instead of creating a new user', () => { + window.localStorage.setItem(USER_ID_STORAGE_KEY, generatedId); + + expect(getUserId()).toBe(generatedId); + expect(crypto.randomUUID).not.toHaveBeenCalled(); + }); + + it('replaces malformed storage with a UUID', () => { + window.localStorage.setItem(USER_ID_STORAGE_KEY, 'not-a-uuid'); + + expect(getUserId()).toBe(generatedId); + expect(window.localStorage.getItem(USER_ID_STORAGE_KEY)).toBe(generatedId); + }); + + it('creates a version 4 UUID when randomUUID is unavailable', () => { + vi.stubGlobal('crypto', { + getRandomValues: (bytes: Uint8Array) => { + bytes.set([...Array(16).keys()]); + return bytes; + }, + }); + + expect(getUserId()).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f'); + }); +}); diff --git a/client/src/api/userIdentity.ts b/client/src/api/userIdentity.ts new file mode 100644 index 0000000..dcc1eb2 --- /dev/null +++ b/client/src/api/userIdentity.ts @@ -0,0 +1,31 @@ +export const USER_ID_STORAGE_KEY = 'crate.user-id'; + +const UUID_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; + +function isUuid(value: string | null): value is string { + return value !== null && UUID_PATTERN.test(value); +} + +function createUuid(): string { + if (typeof crypto.randomUUID === 'function') return crypto.randomUUID(); + + const bytes = crypto.getRandomValues(new Uint8Array(16)); + bytes[6] = (bytes[6]! & 0x0f) | 0x40; + bytes[8] = (bytes[8]! & 0x3f) | 0x80; + const hex = [...bytes].map((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)}`; +} + +/** + * This is a simulated identity, not authentication. It lets the API associate + * a review or crate item with this browser without asking the user to sign in. + */ +export function getUserId(): string { + const existing = window.localStorage.getItem(USER_ID_STORAGE_KEY); + if (isUuid(existing)) return existing.toLowerCase(); + + const userId = createUuid(); + window.localStorage.setItem(USER_ID_STORAGE_KEY, userId); + return userId; +} diff --git a/client/src/components/ReviewForm.css b/client/src/components/ReviewForm.css new file mode 100644 index 0000000..c886ef7 --- /dev/null +++ b/client/src/components/ReviewForm.css @@ -0,0 +1,47 @@ +.review-form { + border-top: 1px solid var(--border); + margin-top: 1.25rem; + padding-top: 1.25rem; +} +.review-form h3 { + font-size: 1rem; +} +.review-form fieldset { + border: 0; + margin: 0 0 1rem; + padding: 0; +} +.review-form legend, +.review-form > label { + display: block; + font-weight: 700; + margin-bottom: 0.4rem; +} +.review-form__ratings { + display: flex; + flex-wrap: wrap; + gap: 0.4rem 0.75rem; +} +.review-form__ratings label { + align-items: center; + display: flex; + gap: 0.25rem; +} +.review-form textarea { + border: 1px solid var(--border); + border-radius: 6px; + display: block; + resize: vertical; + width: 100%; +} +.review-form__actions { + display: flex; + flex-wrap: wrap; + gap: 0.6rem; + margin-top: 1rem; +} +.secondary-button { + background: transparent; + border: 1px solid var(--accent); + color: var(--accent); +} diff --git a/client/src/components/ReviewForm.test.tsx b/client/src/components/ReviewForm.test.tsx new file mode 100644 index 0000000..5703111 --- /dev/null +++ b/client/src/components/ReviewForm.test.tsx @@ -0,0 +1,62 @@ +import { MockedProvider } from '@apollo/client/testing/react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { expect, it, vi } from 'vitest'; + +import { UPSERT_REVIEW } from '../api/reviews.js'; +import ReviewForm from './ReviewForm.js'; + +it('requires an accessible 1 to 5 star choice before it saves', () => { + render( + + + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Publish review' })); + expect(screen.getByRole('alert')).toHaveTextContent( + 'Choose a rating from 1 to 5 stars', + ); + expect(screen.getAllByRole('radio')).toHaveLength(5); + expect(screen.getByRole('radio', { name: '5 stars' })).not.toBeChecked(); + expect(screen.getByRole('textbox', { name: /comment/i })).toHaveAttribute( + 'maxlength', + '2000', + ); +}); + +it('saves the selected rating and optional comment', async () => { + const onChanged = vi.fn(() => Promise.resolve(undefined)); + render( + + + , + ); + + fireEvent.click(screen.getByRole('radio', { name: '5 stars' })); + fireEvent.change(screen.getByRole('textbox', { name: /comment/i }), { + target: { value: 'A classic.' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Publish review' })); + + await waitFor(() => expect(onChanged).toHaveBeenCalledOnce()); + const status = await screen.findByRole('status'); + expect(status).toHaveTextContent('Your review was published.'); + expect(status).toHaveFocus(); +}); diff --git a/client/src/components/ReviewForm.tsx b/client/src/components/ReviewForm.tsx new file mode 100644 index 0000000..80ca9c2 --- /dev/null +++ b/client/src/components/ReviewForm.tsx @@ -0,0 +1,126 @@ +import './ReviewForm.css'; + +import { useEffect, useRef, useState } from 'react'; +import { useMutation } from '@apollo/client/react'; + +import { DELETE_REVIEW, UPSERT_REVIEW } from '../api/reviews.js'; + +type ExistingReview = { id: string; rating: number; comment: string } | null; +const MAX_COMMENT_LENGTH = 2000; + +interface Props { + albumId: string; + review: ExistingReview; + onChanged: () => Promise; +} + +export default function ReviewForm({ albumId, review, onChanged }: Props) { + const [rating, setRating] = useState(review?.rating ?? 0); + const [comment, setComment] = useState(review?.comment ?? ''); + const [error, setError] = useState(null); + const [status, setStatus] = useState(null); + const statusRef = useRef(null); + const [saveReview, saveState] = useMutation(UPSERT_REVIEW); + const [deleteReview, deleteState] = useMutation(DELETE_REVIEW); + const busy = saveState.loading || deleteState.loading; + + useEffect(() => { + if (status) statusRef.current?.focus(); + }, [status]); + + function announce(message: string) { + setStatus(message); + } + + async function submit(event: React.FormEvent) { + event.preventDefault(); + if (rating < 1 || rating > 5) { + setError('Choose a rating from 1 to 5 stars.'); + return; + } + + setError(null); + setStatus(null); + try { + await saveReview({ variables: { input: { albumId, rating, comment } } }); + await onChanged(); + announce(review ? 'Your review was updated.' : 'Your review was published.'); + } catch (caught) { + setError( + caught instanceof Error ? caught.message : 'Your review could not be saved.', + ); + } + } + + async function remove() { + if (!review) return; + setError(null); + setStatus(null); + try { + await deleteReview({ variables: { id: review.id } }); + await onChanged(); + setRating(0); + setComment(''); + announce('Your review was deleted.'); + } catch (caught) { + setError( + caught instanceof Error ? caught.message : 'Your review could not be deleted.', + ); + } + } + + return ( +
void submit(event)}> +

{review ? 'Update your review' : 'Write a review'}

+
+ Rating +
+ {[1, 2, 3, 4, 5].map((value) => ( + + ))} +
+
+ +