Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 48 additions & 23 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<>
Expand All @@ -14,35 +17,57 @@ export default function App() {
</a>
<header className="site-header">
<nav className="navigation" aria-label="Main navigation">
<a className="brand" href={window.location.pathname}>
<a className="brand" href="/">
Crate<span aria-hidden="true">●</span>
</a>
<a href="#catalogue" aria-current="page">
<a href="/" aria-current={detailId ? undefined : 'page'}>
Discover
</a>
</nav>
</header>
<main id="main" tabIndex={-1}>
<section className="search-section" aria-labelledby="search-heading">
<p className="eyebrow">A world of records</p>
<h1 id="search-heading">Discover your next album.</h1>
<p className="tagline">Find something worth listening to.</p>
<SearchForm query={search.query} onSearch={search.search} />
</section>
<div id="catalogue" className="catalogue-layout">
<ResultsLayout
albums={search.albums}
totalCount={search.totalCount}
hasQuery={search.hasQuery}
loading={search.loading}
retrying={search.retrying}
error={search.error}
onRetry={search.retry}
onReset={() => search.search('')}
/>
</div>
</main>
{detailId ? (
<Suspense
fallback={
<main id="main" tabIndex={-1}>
<p role="status">Loading album…</p>
</main>
}
>
<AlbumDetailPage id={detailId} />
</Suspense>
) : (
<DiscoveryPage />
)}
<footer className="site-footer">Crate · Find something worth listening to.</footer>
</>
);
}

function DiscoveryPage() {
const search = useAlbumSearch();

return (
<main id="main" tabIndex={-1}>
<section className="search-section" aria-labelledby="search-heading">
<p className="eyebrow">A world of records</p>
<h1 id="search-heading">Discover your next album.</h1>
<p className="tagline">Find something worth listening to.</p>
<SearchForm query={search.query} onSearch={search.search} />
</section>
<div id="catalogue" className="catalogue-layout">
<ResultsLayout
albums={search.albums}
totalCount={search.totalCount}
hasQuery={search.hasQuery}
loading={search.loading}
retrying={search.retrying}
error={search.error}
onRetry={search.retry}
onReset={() => search.search('')}
/>
</div>
</main>
);
}

const AlbumDetailPage = lazy(() => import('./pages/AlbumDetailPage.js'));
16 changes: 16 additions & 0 deletions client/src/api/albumDetail.test.ts
Original file line number Diff line number Diff line change
@@ -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([]);
});
91 changes: 91 additions & 0 deletions client/src/api/albumDetail.ts
Original file line number Diff line number Diff line change
@@ -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<AlbumDetailData, AlbumDetailVariables> = 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
}
}
}
}
`;
10 changes: 7 additions & 3 deletions client/src/api/client.ts
Original file line number Diff line number Diff line change
@@ -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<AlbumConnection, 'edges'> & {
Expand Down Expand Up @@ -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' })),
});
44 changes: 44 additions & 0 deletions client/src/api/reviews.ts
Original file line number Diff line number Diff line change
@@ -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
}
}
}
`;
33 changes: 33 additions & 0 deletions client/src/api/userIdentity.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
21 changes: 21 additions & 0 deletions client/src/api/userIdentity.ts
Original file line number Diff line number Diff line change
@@ -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;
}
6 changes: 6 additions & 0 deletions client/src/components/AlbumCard.css
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 3 additions & 1 deletion client/src/components/AlbumCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ export default function AlbumCard({ album }: { album: AlbumSummary }) {
return (
<article className="album-card" aria-labelledby={`album-${album.id}`}>
<div className="album-info">
<h3 id={`album-${album.id}`}>{album.title}</h3>
<h3 id={`album-${album.id}`}>
<a href={`/album/${album.id}`}>{album.title}</a>
</h3>
<p className="artist">{album.artists.map((artist) => artist.name).join(', ')}</p>
<p className="release-year">{album.releaseYear ?? 'Year unknown'}</p>
<ul className="genre-tags" aria-label="Genres">
Expand Down
47 changes: 47 additions & 0 deletions client/src/components/ReviewForm.css
Original file line number Diff line number Diff line change
@@ -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);
}
Loading