Skip to content
Merged
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
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

Repository for team IT2810-H26-T19 in IT2810-H26.

**Crate** is an album catalog where users can search for music. The GraphQL API
already supports filtering, sorting and cursor-based pagination, while the
frontend controls for these features are planned for later milestones. Album
details, ratings, reviews and a personal wantlist ("crate") are also planned.
**Crate** is an album catalog where users can search for music, sort and page
through the results, open an album for detail, rate and review it, and add it to
a personal wantlist ("crate"). The GraphQL API also supports genre and decade
filters; the frontend filter controls are planned.

IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks`.

Expand Down Expand Up @@ -228,15 +228,15 @@ 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. The GraphQL backend supports album and artist search, genre and decade filters, sorting and cursor-based pagination. Supported sorts are `RELEVANCE`, `TITLE_ASC` and `RELEASE_YEAR_DESC`. `AVERAGE_RATING_DESC` is defined in the schema but currently returns an error because reviews are not implemented yet.
**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 and decade filters, 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.

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. 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.
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. 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.

**Planned:** Frontend filters and sorting controls; album details; reviews, ratings and wantlist functionality; and Playwright end-to-end tests (M4). The database tables for reviews and crate items exist, but their GraphQL functionality is still planned. `X-User-Id` is also defined but not yet handled at runtime. Accessibility and sustainability are M3 work and are covered under [Sustainability measures](#sustainability-measures) and the accessibility pass in the issue tracker.
**Planned:** Frontend filter controls (#13), 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.

### 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 and decade filters, relevance/title/release-year sorting, facet counts and cursor-based pagination. These capabilities are available through GraphQL but are not all exposed in the frontend yet.
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 and decade filters, relevance/title/release-year/rating sorting, facet counts and cursor-based pagination. Everything except the filters and facet counts is exposed in the frontend.

## Try the application

Expand Down
37 changes: 36 additions & 1 deletion client/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { GraphQLError } from 'graphql';
import App from './App.js';
import { SEARCH_ALBUMS } from './api/searchAlbums.js';
import type {
AlbumSort,
AlbumSummary,
SearchAlbumsData,
SearchAlbumsVariables,
Expand All @@ -25,11 +26,12 @@ const album: AlbumSummary = {
function mockSearch(
query: string,
albums: AlbumSummary[] = [album],
sort: AlbumSort = 'RELEVANCE',
): MockLink.MockedResponse<SearchAlbumsData, SearchAlbumsVariables> {
return {
request: {
query: SEARCH_ALBUMS,
variables: { input: { query, sort: 'RELEVANCE' }, first: 20, after: null },
variables: { input: { query, sort }, first: 20, after: null },
},
result: {
data: {
Expand Down Expand Up @@ -281,6 +283,39 @@ describe('App search', () => {
expect(screen.getByRole('status')).toHaveTextContent('Showing 1 of 1 albums.');
});

it('re-queries the server when the sort changes and keeps it in the URL', async () => {
const lowRated = { ...album, id: '2', title: 'Abbey Lane', averageRating: 2.1 };
renderApp([
mockSearch('Abbey', [lowRated, album]),
mockSearch('Abbey', [album, lowRated], 'AVERAGE_RATING_DESC'),
]);
submitSearch('Abbey');
await screen.findByRole('article', { name: 'Abbey Lane' });
const sort = screen.getByRole('combobox', { name: 'Sort by' });
expect(sort).toHaveValue('RELEVANCE');

fireEvent.change(sort, { target: { value: 'AVERAGE_RATING_DESC' } });

expect(window.location.search).toBe('?q=Abbey&sort=AVERAGE_RATING_DESC');
// The order is whatever the server returned, not a client-side re-sort.
await waitFor(() =>
expect(
screen
.getAllByRole('article')
.map((card) => within(card).getByRole('heading').textContent),
).toEqual(['Abbey Road', 'Abbey Lane']),
);
});

it('restores the sort from a shared link', async () => {
window.history.replaceState({}, '', '/?q=Abbey&sort=RELEASE_YEAR_ASC');
renderApp([mockSearch('Abbey', [album], 'RELEASE_YEAR_ASC')]);
await screen.findByRole('article', { name: 'Abbey Road' });
expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue(
'RELEASE_YEAR_ASC',
);
});

it('replaces results for a new query rather than retaining the previous search', async () => {
renderApp([mockSearch('Abbey'), mockSearch('missing', [])]);
submitSearch('Abbey');
Expand Down
2 changes: 2 additions & 0 deletions client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ function DiscoveryPage() {
albums={search.albums}
totalCount={search.totalCount}
hasQuery={search.hasQuery}
sort={search.sort}
onSortChange={search.setSort}
loading={search.loading}
loadingMore={search.loadingMore}
pageError={search.pageError}
Expand Down
3 changes: 3 additions & 0 deletions client/src/api/searchAlbums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import type { TypedDocumentNode } from '@apollo/client';
export const ALBUM_SORTS = [
'RELEVANCE',
'TITLE_ASC',
'TITLE_DESC',
'RELEASE_YEAR_ASC',
'RELEASE_YEAR_DESC',
'AVERAGE_RATING_ASC',
'AVERAGE_RATING_DESC',
] as const;

Expand Down
7 changes: 7 additions & 0 deletions client/src/components/ResultsLayout.css
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
.results {
padding-bottom: 2.5rem;
}
.results-header {
display: flex;
flex-wrap: wrap;
align-items: baseline;
justify-content: space-between;
gap: 0.5rem 1rem;
}

.pagination {
text-align: center;
Expand Down
12 changes: 10 additions & 2 deletions client/src/components/ResultsLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

import { useEffect, useRef } from 'react';
import AlbumCard from './AlbumCard.js';
import type { AlbumSummary } from '../api/searchAlbums.js';
import SortSelect from './SortSelect.js';
import type { AlbumSort, AlbumSummary } from '../api/searchAlbums.js';

interface Props {
albums: AlbumSummary[];
totalCount: number;
hasQuery: boolean;
sort: AlbumSort;
onSortChange: (sort: AlbumSort) => void;
loading: boolean;
loadingMore: boolean;
pageError: boolean;
Expand Down Expand Up @@ -80,7 +83,12 @@ export default function ResultsLayout(props: Props) {
aria-labelledby="results-heading"
aria-busy={props.loading || props.loadingMore}
>
<h2 id="results-heading">Search results</h2>
<div className="results-header">
<h2 id="results-heading">Search results</h2>
{props.hasQuery && (
<SortSelect sort={props.sort} onSortChange={props.onSortChange} />
)}
</div>
<p role="status" aria-live="polite" className="muted">
{!props.hasQuery
? 'Search for an album or artist to get started.'
Expand Down
17 changes: 17 additions & 0 deletions client/src/components/SortSelect.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
.sort-select {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.9rem;
}
.sort-select label {
color: var(--muted);
}
.sort-select select {
padding: 0.45rem 0.6rem;
border: 1px solid var(--border-strong);
border-radius: 6px;
background: var(--surface);
color: var(--text);
font: inherit;
}
24 changes: 24 additions & 0 deletions client/src/components/SortSelect.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '@testing-library/react';
import SortSelect from './SortSelect.js';
import { ALBUM_SORTS } from '../api/searchAlbums.js';

describe('SortSelect', () => {
it('is labelled and offers every sort the schema accepts', () => {
render(<SortSelect sort="RELEVANCE" onSortChange={vi.fn()} />);
const select = screen.getByRole('combobox', { name: 'Sort by' });
const values = within(select)
.getAllByRole('option')
.map((option) => (option as HTMLOptionElement).value);
expect([...values].sort()).toEqual([...ALBUM_SORTS].sort());
});

it('shows the current sort and reports a change', () => {
const onSortChange = vi.fn();
render(<SortSelect sort="TITLE_ASC" onSortChange={onSortChange} />);
const select = screen.getByRole('combobox', { name: 'Sort by' });
expect(select).toHaveValue('TITLE_ASC');
fireEvent.change(select, { target: { value: 'AVERAGE_RATING_DESC' } });
expect(onSortChange).toHaveBeenCalledExactlyOnceWith('AVERAGE_RATING_DESC');
});
});
60 changes: 60 additions & 0 deletions client/src/components/SortSelect.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import './SortSelect.css';

import { ALBUM_SORTS, type AlbumSort } from '../api/searchAlbums.js';

const LABELS: Record<AlbumSort, string> = {
RELEVANCE: 'Best match',
TITLE_ASC: 'Title A–Z',
TITLE_DESC: 'Title Z–A',
RELEASE_YEAR_DESC: 'Newest first',
RELEASE_YEAR_ASC: 'Oldest first',
AVERAGE_RATING_DESC: 'Highest rated',
AVERAGE_RATING_ASC: 'Lowest rated',
};

// Grouped by what is being sorted rather than in enum order.
const OPTIONS: readonly AlbumSort[] = [
'RELEVANCE',
'TITLE_ASC',
'TITLE_DESC',
'RELEASE_YEAR_DESC',
'RELEASE_YEAR_ASC',
'AVERAGE_RATING_DESC',
'AVERAGE_RATING_ASC',
];

interface Props {
sort: AlbumSort;
onSortChange: (sort: AlbumSort) => void;
}

function isAlbumSort(value: string): value is AlbumSort {
return (ALBUM_SORTS as readonly string[]).includes(value);
}

/**
* A native select, so keyboard and screen reader support come from the
* browser. Changing it only writes the URL: the order itself comes from the
* server, over the whole result set, never from rearranging loaded cards.
*/
export default function SortSelect({ sort, onSortChange }: Props) {
return (
<div className="sort-select">
<label htmlFor="album-sort">Sort by</label>
<select
id="album-sort"
value={sort}
onChange={(event) => {
const next = event.target.value;
if (isAlbumSort(next)) onSortChange(next);
}}
>
{OPTIONS.map((option) => (
<option key={option} value={option}>
{LABELS[option]}
</option>
))}
</select>
</div>
);
}
4 changes: 3 additions & 1 deletion client/src/hooks/useAlbumSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const PAGE_SIZE = 20;
const AUTOMATIC_PAGE_LIMIT = 2;

export function useAlbumSearch() {
const { state, setQuery } = useSearchState();
const { state, setQuery, setSort } = useSearchState();
const query = state.q;
const hasQuery = query.length > 0;
const retryInFlight = useRef(false);
Expand Down Expand Up @@ -174,6 +174,8 @@ export function useAlbumSearch() {

return {
query,
sort: state.sort,
setSort,
search,
hasQuery,
albums: hasQuery
Expand Down
2 changes: 1 addition & 1 deletion client/src/hooks/useSearchState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ describe('parseSearchState', () => {
});

it('falls back to the default sort for a value the schema does not accept', () => {
expect(parseSearchState('?sort=TITLE_DESC').sort).toBe(DEFAULT_SORT);
expect(parseSearchState('?sort=YEAR_DESC').sort).toBe(DEFAULT_SORT);
expect(parseSearchState('?sort=').sort).toBe(DEFAULT_SORT);
expect(parseSearchState('?').sort).toBe(DEFAULT_SORT);
});
Expand Down
3 changes: 3 additions & 0 deletions client/src/pagination.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,9 @@ describe('cursor pagination', () => {
const user = userEvent.setup();
screen.getByRole('button', { name: 'Search' }).focus();

await user.tab();
expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveFocus();

await user.tab();
expect(screen.getByRole('link', { name: 'Album 1' })).toHaveFocus();

Expand Down
2 changes: 2 additions & 0 deletions docs/AI-USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ the part that matters most.
| 2026-10-24 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing cursor pagination, infinite scroll, Load more, Apollo cache handling, and accessibility improvements (#14). |
| 2026-10-25 | rachelks | ChatGPT | Assisted with researching real album datasets, evaluating which data source best fit the project, and planning issues #63 and #64 to implement real data. |
| 2026-10-26 | robertky | Codex (ChatGPT) | Assisted me when I implemented #16: idempotent add/remove mutations, per-request crate-state loading, and accessible list/detail toggles. I reviewed the implementation and test results before using it. |
| 2026-10-26 | evenkkl | Claude | #12, server-side sorting. Read the issue first; it settles the names (`RELEASE_YEAR`, `AVERAGE_RATING`) and that the rating sorts need a stored column, not a live `AVG()`. Claude added the five missing sorts with keyset cursors, `album.average_rating` kept current by a trigger on `review`, the sort control above the results via `setSort`, and tests. I had the trigger and paging across rating ties checked against a real PostgreSQL instance, not only the generated SQL. |
| 2026-10-27 | robertky | Codex (ChatGPT) | Assisted me with #63's MusicBrainz snapshot fetcher, non-destructive catalog import and documentation. |
| 2026-10-28 | evenkkl | Claude | #12, review fixes on #66. Robert asked for an up-to-date branch, a correct README and green CI. Claude merged main, renumbered our migration to `0003` after #63's `0002`, kept both sides of the other conflicts, fixed a duplicate import from the merge, updated the README status sections and added the sort control to the Load more keyboard test. I checked the diff against main contains only our sorting work and these fixes. |

## Notes

Expand Down
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ 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. The supported sort options are `RELEVANCE`, `TITLE_ASC` and `RELEASE_YEAR_DESC`; rating-based sorting is not yet implemented.
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. 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.

## 4. DataLoaders against N+1

Expand Down
6 changes: 6 additions & 0 deletions docs/data-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ details.
artist terms when titles, artist names or artist links change. Migration
`0001` also backfills existing albums.

`album.average_rating` is the mean of the album's review ratings, or NULL without
reviews. A trigger on `review` recomputes it for the one album a review write
touches, so its cost does not grow with the catalog. The rating sorts and
`Album.averageRating` both read it. Migration `0003` adds it and backfills
existing reviews.

## User-generated data

- A **user** is a simulated identity: a UUID the client keeps in `localStorage`
Expand Down
3 changes: 3 additions & 0 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,9 @@ input UpsertReviewInput {
enum AlbumSort {
RELEVANCE
TITLE_ASC
TITLE_DESC
RELEASE_YEAR_ASC
RELEASE_YEAR_DESC
AVERAGE_RATING_ASC
AVERAGE_RATING_DESC
}
Loading