diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index 84dbfb6..ef8fbad 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -179,6 +179,16 @@ describe('App search', () => { expect(window.location.search).toBe('?q=Abbey'); }); + it('returns to an empty discovery page from the main navigation', () => { + window.history.replaceState({}, '', '/?q=Abbey&sort=TITLE_ASC'); + renderApp(); + + expect(screen.getByRole('link', { name: 'Discover' })).toHaveAttribute( + 'href', + import.meta.env.BASE_URL, + ); + }); + it('treats a pasted whitespace-only query as no query at all', async () => { // Without trimming on parse this counted as an active search and went to // the backend, which trimmed it to nothing and returned an empty result. diff --git a/client/src/App.tsx b/client/src/App.tsx index 0f55240..604b836 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -2,10 +2,18 @@ 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 basePath = import.meta.env.BASE_URL.replace(/\/$/, ''); + const discoveryHref = import.meta.env.BASE_URL; + const pathname = window.location.pathname.startsWith(basePath) + ? window.location.pathname.slice(basePath.length) || '/' + : window.location.pathname; + const detailMatch = /^\/album\/(\d+)$/.exec(pathname); + const detailId = detailMatch?.[1]; return ( <> @@ -14,35 +22,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..673388c --- /dev/null +++ b/client/src/api/albumDetail.test.ts @@ -0,0 +1,9 @@ +import schemaSource from '../../../schema.graphql?raw'; +import { buildSchema, validate } from 'graphql'; +import { expect, it } from 'vitest'; + +import { ALBUM_DETAIL } from './albumDetail.js'; + +it('validates the album-detail operation against the repository schema', () => { + expect(validate(buildSchema(schemaSource), ALBUM_DETAIL)).toEqual([]); +}); diff --git a/client/src/api/albumDetail.ts b/client/src/api/albumDetail.ts new file mode 100644 index 0000000..addc6b6 --- /dev/null +++ b/client/src/api/albumDetail.ts @@ -0,0 +1,85 @@ +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; + }; +}; + +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 + reviews(first: $reviewFirst, after: $reviewAfter) { + edges { + cursor + node { + id + rating + comment + createdAt + user { + id + displayName + } + } + } + totalCount + pageInfo { + hasNextPage + endCursor + } + } + } + } +`; 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.test.tsx b/client/src/components/AlbumCard.test.tsx index 70ea9c8..bc6d0a7 100644 --- a/client/src/components/AlbumCard.test.tsx +++ b/client/src/components/AlbumCard.test.tsx @@ -3,6 +3,7 @@ import { render, screen } from '@testing-library/react'; import AlbumCard from './AlbumCard.js'; it('handles nullable summary fields without inventing a rating or year', () => { + window.history.replaceState({}, '', '/?q=Abbey&sort=TITLE_ASC'); render( { expect(screen.getByText('Year unknown')).toBeInTheDocument(); expect(screen.getByText('Not yet rated')).toBeInTheDocument(); expect(screen.getByText('0 reviews')).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Abbey Road' })).toHaveAttribute( + 'href', + `${import.meta.env.BASE_URL}album/1?q=Abbey&sort=TITLE_ASC`, + ); }); diff --git a/client/src/components/AlbumCard.tsx b/client/src/components/AlbumCard.tsx index 20687e4..ae91688 100644 --- a/client/src/components/AlbumCard.tsx +++ b/client/src/components/AlbumCard.tsx @@ -3,10 +3,14 @@ import './AlbumCard.css'; import type { AlbumSummary } from '../api/searchAlbums.js'; export default function AlbumCard({ album }: { album: AlbumSummary }) { + const detailHref = `${import.meta.env.BASE_URL}album/${album.id}${window.location.search}`; + return (
-

{album.title}

+

+ {album.title} +

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

{album.releaseYear ?? 'Year unknown'}

    diff --git a/client/src/pages/AlbumDetailPage.css b/client/src/pages/AlbumDetailPage.css new file mode 100644 index 0000000..b7ddb87 --- /dev/null +++ b/client/src/pages/AlbumDetailPage.css @@ -0,0 +1,85 @@ +.album-detail { + padding-block: 2rem 3rem; +} +.back-link { + color: var(--accent); + font-weight: 700; +} +.album-detail__header { + border-bottom: 1px solid var(--border); + margin: 1.5rem 0; + padding-bottom: 1.5rem; +} +.album-detail__header h1 { + font-size: clamp(2rem, 4vw, 3.5rem); + letter-spacing: -0.05em; + line-height: 1.1; + margin: 0; +} +.album-detail__artists { + font-size: 1.15rem; + margin: 0.5rem 0 0; +} +.album-detail__columns { + display: grid; + gap: 2rem; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); +} +.album-detail h2 { + font-size: 1.25rem; +} +.tracklist, +.review-list { + margin: 1rem 0; + padding: 0; + list-style: none; +} +.tracklist { + counter-reset: tracks; +} +.tracklist li { + border-bottom: 1px solid var(--border); + counter-increment: tracks; + display: flex; + gap: 0.75rem; + justify-content: space-between; + padding: 0.65rem 0; +} +.tracklist li::before { + color: var(--muted); + content: counter(tracks); + min-width: 1.5rem; +} +.tracklist li > span:first-of-type { + flex: 1; +} +.review-list { + display: grid; + gap: 0.8rem; +} +.review-list article { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 8px; + padding: 1rem; +} +.review-list header { + display: flex; + gap: 0.75rem; + justify-content: space-between; +} +.review-list header span { + color: var(--accent); +} +.review-list p { + margin-bottom: 0.5rem; +} +.review-list time { + color: var(--muted); + font-size: 0.85rem; +} +@media (max-width: 700px) { + .album-detail__columns { + grid-template-columns: 1fr; + } +} diff --git a/client/src/pages/AlbumDetailPage.test.tsx b/client/src/pages/AlbumDetailPage.test.tsx new file mode 100644 index 0000000..80619a8 --- /dev/null +++ b/client/src/pages/AlbumDetailPage.test.tsx @@ -0,0 +1,85 @@ +import { MockedProvider } from '@apollo/client/testing/react'; +import { render, screen, within } from '@testing-library/react'; +import { expect, it } from 'vitest'; + +import { ALBUM_DETAIL } from '../api/albumDetail.js'; +import AlbumDetailPage from './AlbumDetailPage.js'; + +const variables = { id: '1', reviewFirst: 10, reviewAfter: null }; + +const detail = { + id: '1', + title: 'Abbey Road', + releaseYear: 1969, + artists: [{ id: '1', name: 'The Beatles' }], + genres: [{ id: '1', name: 'Rock' }], + tracks: [ + { id: '1', title: 'Come Together', trackNumber: 1, durationSeconds: 259 }, + { id: '2', title: 'Something', trackNumber: 2, durationSeconds: null }, + ], + averageRating: 4.5, + reviewCount: 1, + reviews: { + edges: [ + { + cursor: 'cursor-1', + node: { + id: '1', + rating: 5, + comment: 'A classic.', + createdAt: '2026-10-20T12:00:00.000Z', + user: { id: 'user-1', displayName: 'Listener user-1' }, + }, + }, + ], + totalCount: 1, + pageInfo: { hasNextPage: false, endCursor: 'cursor-1' }, + }, +}; + +it('renders an album tracklist and its first page of reviews', async () => { + render( + + + , + ); + + expect(await screen.findByRole('heading', { name: 'Abbey Road' })).toBeInTheDocument(); + const tracklist = screen.getByRole('region', { name: 'Tracklist' }); + expect(within(tracklist).getByText('Come Together')).toBeInTheDocument(); + expect(within(tracklist).getByText('4:19')).toBeInTheDocument(); + expect(within(tracklist).getByText('Something')).toBeInTheDocument(); + const reviews = screen.getByRole('region', { name: 'Reviews' }); + expect(within(reviews).getByText('Listener user-1')).toBeInTheDocument(); + expect(within(reviews).getByText('A classic.')).toBeInTheDocument(); + expect(within(reviews).getByLabelText('5 out of 5 stars')).toBeInTheDocument(); +}); + +it('shows a useful error state when an album cannot be loaded', async () => { + window.history.replaceState({}, '', '/album/1?q=Abbey&sort=TITLE_ASC'); + render( + + + , + ); + + expect(await screen.findByRole('alert')).toHaveTextContent('could not load this album'); + expect(screen.getByRole('link', { name: '← Back to discovery' })).toHaveAttribute( + 'href', + `${import.meta.env.BASE_URL}?q=Abbey&sort=TITLE_ASC`, + ); +}); diff --git a/client/src/pages/AlbumDetailPage.tsx b/client/src/pages/AlbumDetailPage.tsx new file mode 100644 index 0000000..115ae5a --- /dev/null +++ b/client/src/pages/AlbumDetailPage.tsx @@ -0,0 +1,120 @@ +import './AlbumDetailPage.css'; + +import { useQuery } from '@apollo/client/react'; + +import { ALBUM_DETAIL } from '../api/albumDetail.js'; + +const REVIEW_PAGE_SIZE = 10; + +function formatDuration(seconds: number | null): string { + if (seconds === null) return ''; + const minutes = Math.floor(seconds / 60); + return `${minutes}:${String(seconds % 60).padStart(2, '0')}`; +} + +function formatDate(value: string): string { + return new Intl.DateTimeFormat('en', { dateStyle: 'medium' }).format(new Date(value)); +} + +export default function AlbumDetailPage({ id }: { id: string }) { + const { data, loading, error } = useQuery(ALBUM_DETAIL, { + variables: { id, reviewFirst: REVIEW_PAGE_SIZE, reviewAfter: null }, + }); + const discoveryHref = `${import.meta.env.BASE_URL}${window.location.search}`; + + if (loading) { + return ( +
    +

    Loading album…

    +
    + ); + } + + if (error || !data?.album) { + return ( +
    + + ← Back to discovery + +

    Album unavailable

    +

    We could not load this album. Please try again.

    +
    + ); + } + + const { album } = data; + const reviews = album.reviews.edges.map((edge) => edge.node); + + return ( +
    + + ← Back to discovery + +
    +

    Album

    +

    {album.title}

    +

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

    +

    {album.releaseYear ?? 'Release year unknown'}

    +
      + {album.genres.map((genre) => ( +
    • {genre.name}
    • + ))} +
    +
    + +
    +
    +

    Tracklist

    + {album.tracks.length === 0 ? ( +

    No tracklist is available.

    + ) : ( +
      + {album.tracks.map((track) => ( +
    1. + {track.title} + {formatDuration(track.durationSeconds)} +
    2. + ))} +
    + )} +
    + +
    +

    Reviews

    +

    + {album.averageRating === null + ? `Not yet rated · ${album.reviewCount} reviews` + : `${album.averageRating.toFixed(1)} out of 5 · ${album.reviewCount} reviews`} +

    + {reviews.length === 0 ? ( +

    No reviews yet.

    + ) : ( +
      + {reviews.map((review) => ( +
    1. +
      +
      + {review.user.displayName} + + {'★'.repeat(review.rating)} + +
      + {review.comment &&

      {review.comment}

      } + +
      +
    2. + ))} +
    + )} + {album.reviews.pageInfo.hasNextPage && ( +

    More reviews can be loaded when pagination is added.

    + )} +
    +
    +
    + ); +} diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index d5cbdd8..825942d 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -58,6 +58,7 @@ the part that matters most. | 2026-10-19 | erikhfj | opencode | Distributed the M3 issues #11 to #19 across the four of us, then corrected six of them where the text contradicted `schema.graphql` or the M2 identity contract: `toggleCrate` and `inCrate(userId:)` do not exist, `AlbumSort` uses `RELEASE_YEAR` and `AVERAGE_RATING` rather than `YEAR` and `RATING`, `countries` duplicates #25, and the genre facet counts do not exclude their own dimension the way the decade counts do. | | 2026-10-19 | erikhfj | opencode | Reviewed #53 against the code rather than as prose. Found the README contradicting its own Implemented section and a smoke test that dropped an expectation while keeping the field in the query. Verified Rachel's other claims, including that `AVERAGE_RATING_DESC` throws, which corrected my own "four sort modes" in the README. | | 2026-10-19 | erikhfj | opencode | Search state in the URL for #19, with `useSearchState` owning `q`, `sort`, `genres` and `decades`. My first version committed on a 300 ms debounce, which rewrote the URL mid-word and reset the input back through the `query !== previousQuery` branch; it read as the page reloading on every keystroke. Changed so the query reaches the URL only on Search. | +| 2026-10-20 | robertky | Codex (ChatGPT) | Assisted me when I implemented #11: the `album(id:)` resolver, batched loading of album relations, paginated reviews, and a code-split album detail route with tracklist and reviews. I reviewed the parts that AI generated and tests before using it. | ## Notes diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 12b9b7d..c8993c6 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -103,7 +103,9 @@ export const review = pgTable( .references(() => album.id, { onDelete: 'cascade' }), rating: smallint('rating').notNull(), comment: text('comment').notNull().default(''), - createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(), + createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }) + .notNull() + .defaultNow(), updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(), }, (t) => [ diff --git a/server/src/loaders/index.ts b/server/src/loaders/index.ts index e891f0b..96b5c83 100644 --- a/server/src/loaders/index.ts +++ b/server/src/loaders/index.ts @@ -1,9 +1,24 @@ import DataLoader from 'dataloader'; -import { asc, eq, inArray } from 'drizzle-orm'; +import { asc, avg, count, eq, inArray } from 'drizzle-orm'; import type { Db } from '../db/client.js'; -import { albumArtist, albumGenre, artist, genre } from '../db/schema.js'; +import { + albumArtist, + albumGenre, + appUser, + artist, + genre, + review, + track, +} from '../db/schema.js'; type Named = { id: number; name: string }; +export type TrackRecord = { + id: number; + albumId: number; + title: string; + trackNumber: number; + durationSeconds: number | null; +}; /** * DataLoaders for the Album relation fields. Without them a page of 20 albums @@ -35,20 +50,66 @@ export function createLoaders(db: Db) { .orderBy(asc(genre.name)); return groupByAlbum(albumIds, rows); }), + + tracksByAlbum: new DataLoader(async (albumIds) => { + const rows = await db + .select() + .from(track) + .where(inArray(track.albumId, [...albumIds])) + .orderBy(asc(track.trackNumber)); + return groupByAlbum(albumIds, rows); + }), + + reviewCountByAlbum: new DataLoader(async (albumIds) => { + const rows = await db + .select({ albumId: review.albumId, count: count() }) + .from(review) + .where(inArray(review.albumId, [...albumIds])) + .groupBy(review.albumId); + const counts = new Map(rows.map((row) => [row.albumId, Number(row.count)])); + return albumIds.map((id) => counts.get(id) ?? 0); + }), + + averageRatingByAlbum: new DataLoader(async (albumIds) => { + const rows = await db + .select({ albumId: review.albumId, averageRating: avg(review.rating) }) + .from(review) + .where(inArray(review.albumId, [...albumIds])) + .groupBy(review.albumId); + const averages = new Map( + rows.map((row) => [ + row.albumId, + row.averageRating === null ? null : Number(row.averageRating), + ]), + ); + return albumIds.map((id) => averages.get(id) ?? null); + }), + + userById: new DataLoader( + async (userIds) => { + const rows = await db + .select({ id: appUser.id, displayName: appUser.displayName }) + .from(appUser) + .where(inArray(appUser.id, [...userIds])); + const byId = new Map(rows.map((row) => [row.id, row])); + return userIds.map((id) => byId.get(id) ?? null); + }, + ), }; } export type Loaders = ReturnType; // DataLoader needs one result per key, in the same order as the keys. -function groupByAlbum( +function groupByAlbum( albumIds: readonly number[], - rows: (Named & { albumId: number })[], -): Named[][] { - const byAlbum = new Map(); - for (const { albumId, id, name } of rows) { + rows: T[], +): T[][] { + const byAlbum = new Map(); + for (const row of rows) { + const { albumId } = row; const list = byAlbum.get(albumId) ?? []; - list.push({ id, name }); + list.push(row); byAlbum.set(albumId, list); } return albumIds.map((id) => byAlbum.get(id) ?? []); diff --git a/server/src/resolvers.ts b/server/src/resolvers.ts index b5f4d10..f674541 100644 --- a/server/src/resolvers.ts +++ b/server/src/resolvers.ts @@ -1,5 +1,7 @@ -import { sql } from 'drizzle-orm'; +import { and, desc, eq, lt, or, sql } from 'drizzle-orm'; +import { GraphQLError } from 'graphql'; import type { Db } from './db/client.js'; +import { album, review } from './db/schema.js'; import type { Loaders } from './loaders/index.js'; import { afterCursor, @@ -11,12 +13,92 @@ import { sortKey, type AlbumSearchInput, } from './search/search.js'; - export type Context = { db: Db; loaders: Loaders }; type AlbumRow = { id: number; title: string; releaseYear: number | null }; type SearchArgs = { input: AlbumSearchInput; first: number; after?: string | null }; +type AlbumArgs = { id: string }; +type ReviewArgs = { first: number; after?: string | null }; + +type ReviewRow = { + id: number; + userId: string; + albumId: number; + rating: number; + comment: string; + createdAt: string; + updatedAt: Date; +}; + +function parseNumericId(value: string, label: string): number { + const id = Number(value); + if (!Number.isSafeInteger(id) || id < 1) throw new GraphQLError(`Invalid ${label} id.`); + return id; +} + +type ReviewCursor = { createdAt: string; id: number }; + +function encodeReviewCursor(row: ReviewRow): string { + return Buffer.from(JSON.stringify([row.createdAt, row.id])).toString('base64url'); +} + +function decodeReviewCursor(value: string): ReviewCursor { + try { + const parsed: unknown = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')); + if (!Array.isArray(parsed) || parsed.length !== 2) throw new Error(); + const [createdAt, id] = parsed; + if ( + typeof createdAt !== 'string' || + Number.isNaN(Date.parse(createdAt)) || + !Number.isInteger(id) + ) { + throw new Error(); + } + return { createdAt, id }; + } catch { + throw new GraphQLError('Invalid review cursor.'); + } +} + +async function reviewsForAlbum( + ctx: Context, + albumId: number, + { first, after }: ReviewArgs, +) { + const limit = pageSize(first); + const cursor = after ? decodeReviewCursor(after) : null; + const afterCondition = cursor + ? or( + lt(review.createdAt, cursor.createdAt), + and(eq(review.createdAt, cursor.createdAt), lt(review.id, cursor.id)), + ) + : undefined; + const [rows, totalCount] = await Promise.all([ + ctx.db + .select() + .from(review) + .where( + afterCondition + ? and(eq(review.albumId, albumId), afterCondition) + : eq(review.albumId, albumId), + ) + .orderBy(desc(review.createdAt), desc(review.id)) + .limit(limit + 1), + ctx.loaders.reviewCountByAlbum.load(albumId), + ]); + const page = rows.slice(0, limit) as ReviewRow[]; + const edges = page.map((node) => ({ cursor: encodeReviewCursor(node), node })); + + return { + edges, + pageInfo: { + hasNextPage: rows.length > limit, + endCursor: edges.at(-1)?.cursor ?? null, + }, + totalCount, + }; +} /** * searchAlbums runs four queries, all filtered and sorted in SQL so they @@ -78,19 +160,40 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) { }; } -// Fields not listed here (tracks, ratings, reviews, crate) arrive with their -// own issues. +// Search and album detail resolve relations through request-scoped loaders. export const resolvers = { Query: { searchAlbums: (_: unknown, args: SearchArgs, ctx: Context) => searchAlbums(ctx.db, args), + album: async (_: unknown, { id }: AlbumArgs, ctx: Context) => { + const albumId = parseNumericId(id, 'album'); + const [found] = await ctx.db + .select() + .from(album) + .where(eq(album.id, albumId)) + .limit(1); + return found ?? null; + }, }, Album: { artists: (album: AlbumRow, _: unknown, ctx: Context) => ctx.loaders.artistsByAlbum.load(album.id), genres: (album: AlbumRow, _: unknown, ctx: Context) => ctx.loaders.genresByAlbum.load(album.id), - // Required by the schema. Real counts come with the reviews issue. - reviewCount: () => 0, + tracks: (album: AlbumRow, _: unknown, ctx: Context) => + ctx.loaders.tracksByAlbum.load(album.id), + reviewCount: (album: AlbumRow, _: unknown, ctx: Context) => + ctx.loaders.reviewCountByAlbum.load(album.id), + averageRating: (album: AlbumRow, _: unknown, ctx: Context) => + ctx.loaders.averageRatingByAlbum.load(album.id), + reviews: (album: AlbumRow, args: ReviewArgs, ctx: Context) => + reviewsForAlbum(ctx, album.id, args), + }, + Review: { + user: async (review: { userId: string }, _: unknown, ctx: Context) => { + const user = await ctx.loaders.userById.load(review.userId); + if (!user) throw new Error('Review owner is missing.'); + return user; + }, }, };