diff --git a/AGENTS.md b/AGENTS.md index b933680..598fd1a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,9 @@ personal wantlist ("crate"). IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks`. -**Status: M2 – PostgreSQL and GraphQL.** The frontend supports album and artist search, while the backend implements searching, filtering, sorting and pagination. Album details, reviews, crate functionality, simulated user identity and additional frontend controls are planned for later milestones. See the README for current implementation status. +**Status: M3 – Functional beta.** See the README's +[implementation status](README.md#implementation-status) for implemented features +and planned work. ## Commands @@ -43,10 +45,10 @@ requirements work - do not casually change them. from a field resolver. 4. **User input is never interpolated into SQL.** Use parameterised queries. 5. **Users are simulated.** A UUID in `localStorage`, sent as an `X-User-Id` - header on **every** request, not just mutations. `myReview`, `isInCrate` and - `myCrate` are queries and need it just as much. The server reads the header - once into the GraphQL context, so no field in `schema.graphql` takes a - `userId` argument. No authentication. + header on **every** request, not just mutations. The implemented `myReview` + and `isInCrate` fields, as well as the planned `myCrate` query, rely on + this identity. The server reads the header once into the GraphQL context, + so no field in `schema.graphql` takes a `userId` argument. No authentication. - Missing or malformed id means **anonymous**: reads degrade to `null` or `false`, mutations that need identity fail with a clear error. - The context is **per request**. Hoisting the user id into a module-level diff --git a/README.md b/README.md index ada5139..71f69a2 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,8 @@ CI also builds the project and checks the client bundle size. | `pnpm db:fetch:musicbrainz` | Rebuild the local MusicBrainz snapshot (network required) | | `pnpm db:seed:large` | Reset to a large synthetic catalog | -Unit tests cover frontend components and backend logic, but do not test a running PostgreSQL database. The [VM setup guide](docs/VM-setup.md) includes API smoke tests. +Tests cover frontend components and backend logic. Additional PostgreSQL tests cover search, sorting, rating updates and filters. These run when `TEST_DATABASE_URL` is configured and require a separate test database with migrations applied. The +[VM setup guide](docs/VM-setup.md) includes API smoke tests. ## Database seed data @@ -180,6 +181,12 @@ Measurements are based on two local runs with cached synthetic data and cover on The read-only benchmark is available in `server/scripts/prefix-search-perf.sql`. PostgreSQL tests can be run by setting `TEST_DATABASE_URL` before running the server tests. +### Accessibility + +The interface supports keyboard navigation, visible focus indicators, labelled form controls and a skip link to the main content. Search results, loading states and errors provide feedback to assistive technologies. The layout adapts to smaller screens and respects reduced-motion preferences. + +Automated accessibility tests use axe-core to check key search states, including initial, results, no-results and error views. Component tests also cover keyboard interactions and focus behavior. Since these tests run in jsdom, they cannot fully verify visual accessibility, such as color contrast and layout at different zoom levels. Manual browser testing is still needed. + ### Sustainability measures We consider sustainability through design choices that reduce unnecessary data transfer, processing and resource use, while acknowledging performance tradeoffs. @@ -189,10 +196,10 @@ We consider sustainability through design choices that reduce unnecessary data t | Plain CSS, no UI framework | No component-library runtime to download or parse | 0 UI dependencies in the bundle | | `prefers-color-scheme` | OLED screens draw less power on a dark pixel | Dark theme when the OS asks for it | | `prefers-reduced-motion` | Animations cost frames and battery | Collapsed to near-zero when the OS asks for it | -| Nothing until Search is pressed | Typing would otherwise cost one request per change | `skipToken` holds the query back, so typing is free | -| `cache-first` fetch policy | A repeated search is already in the cache | 0 requests when the answer is cached | +| Explicit search submission | Typing would otherwise cost one request per change | Typing sends no search requests; Search or Enter commits the query | +| `cache-first` fetch policy | A repeated search is already in the cache | No request when the complete requested result is cached | | Cursor pagination and cached pages | Load only the next batch and reuse pages already fetched | 20 albums per page; 0 requests to reveal cached pages | -| Code-split album route | The detail page is not needed to browse search results | Separate 3.73 kB chunk, kept out of the main bundle | +| Code-split album route | The detail page is not needed to browse search results | Separate detail chunks; see dated measurements below | | Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | | Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, but potentially higher query costs for broad prefixes | @@ -206,7 +213,7 @@ We consider sustainability through design choices that reduce unnecessary data t | `AlbumDetailPage-*.css` | 1.94 kB | 0.71 kB | | `index.html` | 0.51 kB | 0.31 kB | -The two `AlbumDetailPage` rows represent the separate chunks for the album detail route and are not part of the search page payload. The album link currently causes a full page load, so opening an album also reloads the main bundle. +The two `AlbumDetailPage` rows represent the separate chunks for the album detail route and are not part of the search page payload. Opening an album uses normal page navigation, while previously downloaded assets may be reused by the browser. **Requests for a typical search:** An uncached search initially fetches up to 20 albums in one `searchAlbums` request. Infinite scroll loads up to two additional pages automatically, while further pages are loaded using the Load more button. Previously fetched pages are reused from Apollo's cache without new requests. No search requests are sent while the user types. @@ -228,15 +235,24 @@ The two `AlbumDetailPage` rows represent the separate chunks for the album detai | `schema.graphql` | GraphQL schema | | `docs/` | Architecture, data model, UI, workflow, AI log and VM guide | -**Implemented:** The PostgreSQL database includes albums, artists, genres, tracks, users, reviews and crate items, with a real catalog imported from MusicBrainz. The GraphQL backend supports album and artist search, genre, decade and has-reviews filters with facet counts, sorting, cursor-based pagination, album details, reviews and adding or removing albums from the crate. Users are simulated: the client sends an `X-User-Id` header on every request and the server reads it into the request context. Supported sorts are `RELEVANCE`, `TITLE_ASC`, `TITLE_DESC`, `RELEASE_YEAR_ASC`, `RELEASE_YEAR_DESC`, `AVERAGE_RATING_ASC` and `AVERAGE_RATING_DESC`, chosen from the sort control above the results. +## Implementation status + +**Search and filtering:** Users can search for albums by title or artist using Search or Enter. Results can be sorted by relevance, title, release year or average rating, and filtered by genre, decade or whether an album has reviews. Search terms, sorting and filters are preserved in the URL. + +**Results and pagination:** Searches initially display up to 20 albums. Additional results load automatically as the user scrolls, up to 60 albums. Load more is also available before this limit; further pages require the button. The interface provides loading, error and no-results feedback. + +**Album details and reviews:** Album pages display tracks, average ratings and reviews. Users can write, edit and delete their own reviews. -The frontend supports searching by album title or artist, committed on Search or Enter rather than while typing, with loading and error feedback, and a no-results message. Searches start with 20 visible matches ordered by relevance, and the sort control re-queries the server so the new order covers the whole result set. The sort is kept in the URL with the query. Infinite scroll reveals up to 60 matches, then Load more reveals subsequent pages. Returning to a search starts with 20 visible matches and reuses cached pages before requesting more. A Filters button above the results opens a panel that narrows them by genre, decade and whether an album has reviews. Genres combine with AND, so a genre's count is how many albums would remain after ticking it. Decades combine with OR, so a decade's count is how many matching albums that decade has, and ticking another decade adds them to the selection. Options with no matches are hidden, but selected ones always stay so they can be removed. Changing a filter starts again from the first page. Opening an album shows its tracks, average rating and reviews, and lets the user write, edit or delete their own review. Albums can be added to or removed from the crate from the results and the album page. +**Personal crate:** Users can add or remove albums from their crate on both search results and album detail pages. User identity is simulated using a locally stored ID rather than a login system. -**Planned:** A page listing the user's crate (`myCrate`), and Playwright end-to-end tests (M4). Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker. +**Planned for M4:** A page for viewing all albums saved in the user's crate, the supporting `myCrate` query, and Playwright end-to-end tests. Browsing albums without entering a search term is also planned. ### Backend search behavior -The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre, decade and has-reviews filters, relevance/title/release-year/rating sorting, facet counts and cursor-based pagination. All of it is exposed in the frontend. +The API uses PostgreSQL full-text search with prefix matching (e.g. `radi` +matches `Radiohead`). SQL handles sorting, filtering, facet counts and cursor +pagination; see the [architecture decisions](docs/architecture.md#3-sorting-and-filtering-in-sql) +for details. ## Try the application diff --git a/client/src/App.css b/client/src/App.css index 936c93b..e9bd5ab 100644 --- a/client/src/App.css +++ b/client/src/App.css @@ -41,7 +41,7 @@ } #main { max-width: 1240px; - padding: 0 2rem; + padding-inline: 2rem; margin: auto; } .search-section { diff --git a/client/src/components/AlbumCard.css b/client/src/components/AlbumCard.css index 88c550d..60819f1 100644 --- a/client/src/components/AlbumCard.css +++ b/client/src/components/AlbumCard.css @@ -14,7 +14,7 @@ } .album-info h3 { margin: 0; - font-size: 1rem; + font-size: 1.1rem; line-height: 1.4; overflow-wrap: anywhere; } diff --git a/client/src/components/CrateButton.css b/client/src/components/CrateButton.css index 18ed7c9..40072b5 100644 --- a/client/src/components/CrateButton.css +++ b/client/src/components/CrateButton.css @@ -8,10 +8,18 @@ color: var(--danger, #a32626); font-size: 0.85rem; } -.crate-button--saved { +.crate-button { + background: transparent; + border: 1px solid var(--accent); + color: var(--accent); +} +.crate-button:not(.crate-button--saved):not(:disabled):hover { + background: var(--chip-bg); +} +.crate-button.crate-button--saved { background: var(--accent); color: var(--accent-text); } -.crate-button--saved:hover { +.crate-button--saved:not(:disabled):hover { background: var(--accent-hover); } diff --git a/client/src/components/ReviewForm.css b/client/src/components/ReviewForm.css index c886ef7..0c58c76 100644 --- a/client/src/components/ReviewForm.css +++ b/client/src/components/ReviewForm.css @@ -24,13 +24,19 @@ } .review-form__ratings label { align-items: center; + cursor: pointer; display: flex; gap: 0.25rem; + padding: 0.35rem 0.5rem; } .review-form textarea { + background: var(--surface); border: 1px solid var(--border); border-radius: 6px; + color: var(--text); display: block; + font: inherit; + padding: 0.65rem 0.75rem; resize: vertical; width: 100%; } diff --git a/client/src/pages/AlbumDetailPage.test.tsx b/client/src/pages/AlbumDetailPage.test.tsx index 17d005a..c223004 100644 --- a/client/src/pages/AlbumDetailPage.test.tsx +++ b/client/src/pages/AlbumDetailPage.test.tsx @@ -64,6 +64,38 @@ it('renders an album tracklist and its first page of reviews', async () => { expect(within(reviews).getByLabelText('5 out of 5 stars')).toBeInTheDocument(); }); +it.each([ + ['1', 'You'], + ['2', 'Listener user-1'], +])('labels a review with own review ID %s as %s', async (ownReviewId, authorLabel) => { + render( + + + , + ); + + const reviews = await screen.findByRole('region', { name: 'Reviews' }); + const review = within(reviews).getByRole('article'); + expect(within(review).getByText(authorLabel)).toBeInTheDocument(); + expect( + within(review).queryByText(authorLabel === 'You' ? 'Listener user-1' : 'You'), + ).not.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( @@ -86,9 +118,11 @@ it('shows a useful error state when an album cannot be loaded', async () => { ); }); -it('loads the next page of reviews on request', async () => { +it('loads the next page of reviews and labels an own review as You', async () => { + const myReview = { id: '2', rating: 4, comment: 'Still brilliant.' }; const firstPage = { ...detail, + myReview, reviewCount: 2, reviews: { ...detail.reviews, @@ -98,6 +132,7 @@ it('loads the next page of reviews on request', async () => { }; const secondPage = { ...detail, + myReview, reviewCount: 2, reviews: { edges: [ @@ -137,10 +172,17 @@ it('loads the next page of reviews on request', async () => { ); await screen.findByRole('heading', { name: 'Abbey Road' }); + expect(screen.getByText('Listener user-1')).toBeInTheDocument(); + expect(screen.queryByText('You')).not.toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Load more reviews' })); - expect(await screen.findByText('Still brilliant.')).toBeInTheDocument(); + expect(await screen.findByText('You')).toBeInTheDocument(); + const articles = screen.getAllByRole('article'); + expect(articles).toHaveLength(2); + expect(within(articles[1]!).getByText('Still brilliant.')).toBeInTheDocument(); expect(screen.getByText('A classic.')).toBeInTheDocument(); + expect(screen.getByText('Listener user-1')).toBeInTheDocument(); + expect(screen.queryByText('Listener user-2')).not.toBeInTheDocument(); expect( screen.queryByRole('button', { name: 'Load more reviews' }), ).not.toBeInTheDocument(); diff --git a/client/src/pages/AlbumDetailPage.tsx b/client/src/pages/AlbumDetailPage.tsx index e637e22..a32170a 100644 --- a/client/src/pages/AlbumDetailPage.tsx +++ b/client/src/pages/AlbumDetailPage.tsx @@ -137,7 +137,11 @@ export default function AlbumDetailPage({ id }: { id: string }) {
  • - {review.user.displayName} + + {review.id === album.myReview?.id + ? 'You' + : review.user.displayName} + {'★'.repeat(review.rating)} diff --git a/docs/VM-setup.md b/docs/VM-setup.md index 594cac6..d560b7b 100644 --- a/docs/VM-setup.md +++ b/docs/VM-setup.md @@ -1,6 +1,6 @@ # VM setup -How to deploy the Crate application on the group VM and verify that it works. +How to update and verify the Crate application deployed on the group VM. ## Deployment setup @@ -27,6 +27,8 @@ pnpm --filter @t19/server build sudo /usr/bin/systemctl restart crate-api ``` +To populate the catalog initially or import an updated MusicBrainz snapshot, run `pnpm --filter @t19/server db:import:musicbrainz`. Existing reviews and crate items are preserved. + The database and role must already exist before migrations are run. The API runs on port 3001 and needs the repository's `schema.graphql` file at startup. @@ -60,6 +62,7 @@ curl -fsS -o /dev/null -w '%{http_code}\n' http://localhost/project2/ Then run the smoke tests below against the API and, if needed, through Apache. You can also open and try an album search. +Open an album detail URL directly and reload the page to verify that routing works correctly. ### Optional sample data @@ -84,9 +87,11 @@ endpoint, set `VITE_GRAPHQL_URL` in `client/.env.local`. ## Smoke suite -Run these commands on the VM after deployment. The expected counts below assume -the sample catalog from `db:seed`; counts may differ if the database contains -other data. Check each response for GraphQL `errors`. +The smoke tests below were originally written for the sample catalog created by `db:seed`. Some expected album names, counts and genre IDs do not match the deployed MusicBrainz catalog. + +**TODO (M4):** Update the smoke tests and expected results to use the MusicBrainz catalog. + +Until then, the tests can be used to check API functionality, but sample-specific results should not be treated as expected values on the VM. Check each response for GraphQL `errors`. ```bash API=http://localhost:3001/graphql diff --git a/docs/architecture.md b/docs/architecture.md index 17ddcc8..0473ff6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,8 +5,6 @@ in M2 and M3. The API contract is `schema.graphql`, the data model is in `docs/data-model.md`, and the planned interface is described in `docs/ui-specification.md`. -At M2, search, filtering, sorting, pagination and DataLoaders are implemented in the backend. URL-based search state landed in M3. User identity, reviews and crate functionality are planned for later milestones. - ## 1. PostgreSQL + GraphQL Yoga **Context:** The data is relational. Albums have many artists and genres, and @@ -41,6 +39,8 @@ it can repeat or skip rows when data changes between requests. forward, so there is no "jump to page N". Each sort mode needs its own cursor logic, including nullable fields such as release year. +When sorting by average rating, review changes between page requests can affect the order of results. This means cursor pagination does not guarantee that every album appears exactly once if ratings change while browsing. + ## 3. Sorting and filtering in SQL **Context:** Sorting and filtering must apply to the whole result set, not just @@ -57,7 +57,9 @@ resolver loads every match into memory. builder is the most complex server code, so it needs tests against a real database. -The implemented search uses PostgreSQL full-text search with weighted album titles and artist names. Genre filters combine with AND, while decade filters combine with OR. Counts and facets cover matching results, not just the current page. Genre counts use the full filter, because with AND they then equal what ticking the genre gives. Decade counts and the reviewed count leave out their own filter, since those combine with OR or are a single switch. The filter panel hides options with a count of zero, so a click never leads to an empty page. Sorting covers relevance, title, release year and average rating, the last three in both directions. Every sort ends with an `album.id` tiebreak and puts NULLs last, so the keyset cursor stays stable. The rating sorts read `album.average_rating`, a column a trigger on `review` keeps current, because a live `AVG()` would be recomputed for the whole result set and would move under a cursor whenever someone saved a review. +The implemented search uses PostgreSQL full-text search with weighted album titles and artist names. Genre filters combine with AND, while decade filters combine with OR. Counts and facets cover matching results, not just the current page. Genre counts use the full filter, because with AND they then equal what ticking the genre gives. Decade counts and the reviewed count leave out their own filter, since those combine with OR or are a single switch. The filter panel hides unselected options with zero matches, while selected filters remain available so users can remove them. + +Sorting supports relevance, title, release year and average rating. Each sort uses album.id as a tiebreaker and places NULL values last. Average ratings are stored and updated when reviews change, avoiding repeated calculations during searches. ## 4. DataLoaders against N+1 @@ -94,17 +96,11 @@ brief explicitly wants simulated users rather than login. Not an `Authorization` header either, because nothing here is authenticated and calling it that would be misleading. -It goes on **every** request, not only mutations. Those three fields are -queries. - -**Missing or invalid.** Absent or malformed means anonymous. +It goes on **every** request, not only mutations: `myReview` and `isInCrate` +are query fields. The same transport is intended for `myCrate`, which is declared +in the schema but has no resolver yet. -| State | `myReview` | `isInCrate` | `myCrate` | Mutations | -| ----------------- | ---------- | ----------- | ---------------- | ------------------------ | -| No header | `null` | `false` | empty connection | error: no client id | -| Malformed | `null` | `false` | empty connection | error: invalid client id | -| Valid, no row yet | `null` | `false` | empty connection | succeed, create the row | -| Valid, row exists | the review | as stored | the crate | succeed | +**Missing or invalid user ID.** If the `X-User-Id` header is missing or invalid, the application treats the user as anonymous. Their own review is returned as `null`, and albums are treated as not being in their crate. Adding albums or saving reviews requires a valid user ID. Reads never fail because of identity state, so a bad header cannot take the search page down. Writes require it and say so rather than attributing the @@ -115,8 +111,7 @@ UUID in `X-User-Id` writes as that user, so this separates visitors rather than authenticating them. Deriving `displayName` from the UUID stops the client choosing an arbitrary name string and stops a review claiming a display name the sender did not hold, but it does **not** stop impersonation: the UUID is -the whole identity and it is client-supplied. Clearing storage gives a new -user. +the whole identity and it is client-supplied. Clearing `localStorage` resets the user's identity in the browser, but their existing reviews and crate items remain in the database. ## 6. Plain CSS, Apollo Client cache, URL as search state @@ -130,12 +125,7 @@ in the URL. **Decision:** - **Plain CSS** for a smaller bundle and full control over focus and contrast. -- **The Apollo cache** as the store for server data. Mutations return the - updated album, so Apollo updates that album's cached data without a refetch. - Related lists such as `myCrate` and `reviews` may still need a cache update or - refetch. +- **The Apollo cache** stores data received from the server. Adding or removing an album from the crate updates its cached state, while review changes trigger a refresh of the album details. - **The URL** holds the search term, sort and filters (genres, decades and `reviewed`). -**Consequences:** We write all the styling ourselves. There is one source of -truth for server data. Reload, back/forward and shared links reproduce the same -search. +**Consequences:** We write all the styling ourselves. Apollo Client manages server data, while the URL preserves search terms, filters and sorting so searches can be shared or revisited. diff --git a/docs/data-model.md b/docs/data-model.md index be18e74..b9cc70a 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -1,6 +1,7 @@ # Crate data model -This document describes the model behind `schema.graphql`. The M2 database migrations implement the catalog and user-related tables. Currently, only album search and artist/genre relations are available through GraphQL resolvers. The user interactions described below are planned for later milestones. +This document describes the entities, relationships and constraints behind +`schema.graphql` and the PostgreSQL database. ## Core catalog @@ -51,7 +52,9 @@ existing reviews. - A **review** belongs to one album and one simulated user. A user can have one review per album, so saving another review updates the existing one. Album details can also return the current user's review to prefill an edit form, - and each review carries the `User` who wrote it. + and each review carries the `User` who wrote it. Ratings are integers from 1 + to 5, comments are optional (up to 2,000 characters), and users can delete + their own reviews. - A **crate item** belongs to one simulated user and one album. It represents the user's personal wantlist. The schema has separate add and remove actions so repeated requests cannot accidentally switch the album back to the wrong @@ -59,10 +62,8 @@ existing reviews. The tables exist, with unique `(user_id, album_id)` pairs for reviews and crate items, a rating check of 1-5, and a trigger updating `review.updated_at`. -Identity transport, display-name derivation and review/crate resolvers are -not implemented. The schema describes the operations the client will need. See -[`docs/architecture.md`](./architecture.md) decision 5 for how the identity -travels and what happens when it is missing. +See +[`docs/architecture.md`](./architecture.md) decision 5 for how the identity travels and what happens when it is missing. ## Search results diff --git a/docs/ui-specification.md b/docs/ui-specification.md index 85ebf02..0415d21 100644 --- a/docs/ui-specification.md +++ b/docs/ui-specification.md @@ -2,7 +2,18 @@ This document describes the planned user interface for Crate, an album catalogue application. It includes example data, wireframes and a visual design concept to guide the ongoing frontend implementation. -The initial search interface has been implemented, while additional features and visual refinements are planned for later development stages. +The sketches and descriptions below represent the original design concept. Some parts of the interface have changed during implementation, and the example ratings and review counts are illustrative. + +## M3 implementation notes + +- Searches are submitted using the Search button or Enter, rather than automatically while typing. +- The Discover page currently shows no albums before a search. For M4, we plan to explore displaying initial content, such as featured or recently released albums, so users can browse and filter by genre without entering a search term. +- Filters are presented in a dropdown instead of a permanent sidebar. Active-filter chips from the original sketches have not been implemented. +- Sorting and pagination are implemented, with additional results loading automatically at first and a Load more button for further results. +- Album details, reviews and crate add/remove functionality are implemented. Some visual elements from the sketches, such as album artwork and a separate rating action, are not included. + +See the README's [implementation status](../README.md#implementation-status) for +the current feature overview and planned work. ## Visual design concept