diff --git a/client/src/App.tsx b/client/src/App.tsx index 0f55240..a20881b 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -2,10 +2,13 @@ import SearchForm from './components/SearchForm.js'; import ResultsLayout from './components/ResultsLayout.js'; +import { lazy, Suspense } from 'react'; + import { useAlbumSearch } from './hooks/useAlbumSearch.js'; export default function App() { - const search = useAlbumSearch(); + const detailMatch = /^\/album\/(\d+)$/.exec(window.location.pathname); + const detailId = detailMatch?.[1]; return ( <> @@ -14,35 +17,57 @@ export default function App() {
-
-
-

A world of records

-

Discover your next album.

-

Find something worth listening to.

- -
-
- search.search('')} - /> -
-
+ {detailId ? ( + +

Loading album…

+ + } + > + +
+ ) : ( + + )} ); } + +function DiscoveryPage() { + const search = useAlbumSearch(); + + return ( +
+
+

A world of records

+

Discover your next album.

+

Find something worth listening to.

+ +
+
+ search.search('')} + /> +
+
+ ); +} + +const AlbumDetailPage = lazy(() => import('./pages/AlbumDetailPage.js')); diff --git a/client/src/api/albumDetail.test.ts b/client/src/api/albumDetail.test.ts new file mode 100644 index 0000000..108b54f --- /dev/null +++ b/client/src/api/albumDetail.test.ts @@ -0,0 +1,16 @@ +import schemaSource from '../../../schema.graphql?raw'; +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 new file mode 100644 index 0000000..693b704 --- /dev/null +++ b/client/src/api/albumDetail.ts @@ -0,0 +1,91 @@ +import { gql } from '@apollo/client'; +import type { TypedDocumentNode } from '@apollo/client'; + +export type AlbumDetail = { + id: string; + title: string; + releaseYear: number | null; + artists: { id: string; name: string }[]; + genres: { id: string; name: string }[]; + tracks: { + id: string; + title: string; + trackNumber: number; + durationSeconds: number | null; + }[]; + averageRating: number | null; + reviewCount: number; + reviews: { + edges: { + cursor: string; + node: { + id: string; + rating: number; + comment: string; + createdAt: string; + user: { id: string; displayName: string }; + }; + }[]; + pageInfo: { hasNextPage: boolean; endCursor: string | null }; + totalCount: number; + }; + myReview: { id: string; rating: number; comment: string } | null; +}; + +type AlbumDetailData = { album: AlbumDetail | null }; +type AlbumDetailVariables = { + id: string; + reviewFirst: number; + reviewAfter?: string | null; +}; + +export const ALBUM_DETAIL: TypedDocumentNode = gql` + query AlbumDetail($id: ID!, $reviewFirst: Int!, $reviewAfter: String) { + album(id: $id) { + id + title + releaseYear + artists { + id + name + } + genres { + id + name + } + tracks { + id + title + trackNumber + durationSeconds + } + averageRating + reviewCount + myReview { + id + rating + comment + } + reviews(first: $reviewFirst, after: $reviewAfter) { + edges { + cursor + node { + id + rating + comment + createdAt + user { + id + displayName + } + } + } + totalCount + pageInfo { + hasNextPage + endCursor + } + } + } + } +`; diff --git a/client/src/api/client.ts b/client/src/api/client.ts index ac1dc72..e9d2773 100644 --- a/client/src/api/client.ts +++ b/client/src/api/client.ts @@ -1,7 +1,9 @@ import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'; import type { Reference, StoreObject } from '@apollo/client'; +import { setContext } from '@apollo/client/link/context'; import type { AlbumConnection } from './searchAlbums.js'; +import { getUserId } from './userIdentity.js'; // Album nodes are normalized references inside the cache, not query-result objects. type CachedConnection = Omit & { @@ -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..cc631a6 --- /dev/null +++ b/client/src/api/userIdentity.test.ts @@ -0,0 +1,33 @@ +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()); + +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); + }); +}); diff --git a/client/src/api/userIdentity.ts b/client/src/api/userIdentity.ts new file mode 100644 index 0000000..a2e584a --- /dev/null +++ b/client/src/api/userIdentity.ts @@ -0,0 +1,21 @@ +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); +} + +/** + * 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 = crypto.randomUUID(); + window.localStorage.setItem(USER_ID_STORAGE_KEY, userId); + return userId; +} diff --git a/client/src/components/AlbumCard.css b/client/src/components/AlbumCard.css index b9c6d5a..9518aa4 100644 --- a/client/src/components/AlbumCard.css +++ b/client/src/components/AlbumCard.css @@ -18,6 +18,12 @@ line-height: 1.4; overflow-wrap: anywhere; } +.album-info h3 a { + text-decoration: none; +} +.album-info h3 a:hover { + text-decoration: underline; +} .artist { margin: 0.25rem 0; color: var(--muted); diff --git a/client/src/components/AlbumCard.tsx b/client/src/components/AlbumCard.tsx index 20687e4..0b04a47 100644 --- a/client/src/components/AlbumCard.tsx +++ b/client/src/components/AlbumCard.tsx @@ -6,7 +6,9 @@ export default function AlbumCard({ album }: { album: AlbumSummary }) { return (
-

{album.title}

+

+ {album.title} +

{album.artists.map((artist) => artist.name).join(', ')}

{album.releaseYear ?? 'Year unknown'}

    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..fb82688 --- /dev/null +++ b/client/src/components/ReviewForm.test.tsx @@ -0,0 +1,55 @@ +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(); +}); + +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()); +}); diff --git a/client/src/components/ReviewForm.tsx b/client/src/components/ReviewForm.tsx new file mode 100644 index 0000000..89878f5 --- /dev/null +++ b/client/src/components/ReviewForm.tsx @@ -0,0 +1,99 @@ +import './ReviewForm.css'; + +import { 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; + +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 [saveReview, saveState] = useMutation(UPSERT_REVIEW); + const [deleteReview, deleteState] = useMutation(DELETE_REVIEW); + const busy = saveState.loading || deleteState.loading; + + 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); + try { + await saveReview({ variables: { input: { albumId, rating, comment } } }); + await onChanged(); + } catch { + setError('Your review could not be saved. Please try again.'); + } + } + + async function remove() { + if (!review) return; + setError(null); + try { + await deleteReview({ variables: { id: review.id } }); + await onChanged(); + } catch { + setError('Your review could not be deleted. Please try again.'); + } + } + + return ( +
    void submit(event)}> +

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

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