Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,15 +194,15 @@ The two `AlbumDetailPage` rows are the chunk added by the album detail route (#1
| `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. The GraphQL backend supports album and artist search, genre and decade filters, sorting and cursor-based pagination. 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. It currently shows the first 20 matches ordered by relevance.

**Planned:** Frontend filters, sorting and pagination 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.

### 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. These capabilities are available through GraphQL but are not all exposed in the frontend yet.

## 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 @@ -24,11 +25,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 @@ -273,6 +275,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}
retrying={search.retrying}
error={search.error}
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;
}
.album-grid {
list-style: none;
margin: 0;
Expand Down
12 changes: 10 additions & 2 deletions client/src/components/ResultsLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import './ResultsLayout.css';

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;
retrying: boolean;
error: boolean;
Expand All @@ -21,7 +24,12 @@ export default function ResultsLayout(props: Props) {
aria-labelledby="results-heading"
aria-busy={props.loading}
>
<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 @@ -8,7 +8,7 @@ import { useSearchState } from './useSearchState.js';
const PAGE_SIZE = 20;

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 @@ -67,6 +67,8 @@ export function useAlbumSearch() {

return {
query,
sort: state.sort,
setSort,
search,
hasQuery,
albums: hasQuery ? (data?.searchAlbums.edges.map((edge) => edge.node) ?? []) : [],
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
1 change: 1 addition & 0 deletions docs/AI-USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ the part that matters most.
| 2026-10-22 | erikhfj | opencode | #18, dark theme under `prefers-color-scheme`. Lifted the eight hard-coded colours into custom properties first so the light palette stays byte-identical. Did not take the generated palette as-is: `--border-strong` at `#556055` measured 2.5:1 against the surface, under the 3:1 a form-control border needs, so it became `#6b766b` at 3.4:1. Computed every ratio by hand rather than trusting the values that came back. |
| 2026-10-22 | erikhfj | opencode | #17, axe-core over all four states of the search page. A green suite proves nothing on its own, so the harness asserts axe found passing rules before asserting it found no violations, and I checked it against a deliberately broken tree first to confirm it reports failures. `color-contrast` is disabled because jsdom paints nothing; that limitation is written into the PR rather than quietly omitted. |
| 2026-10-23 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing prefix search (#55), performance testing with 100,000 albums, and updating documentation. |
| 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. |

## 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 @@ -21,6 +21,12 @@ genre and join tables.
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 `0002` 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
}
48 changes: 48 additions & 0 deletions server/drizzle/0002_album-average-rating.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
ALTER TABLE "album" ADD COLUMN "average_rating" double precision;
--> statement-breakpoint
CREATE FUNCTION refresh_album_average_rating(target_album_id integer)
RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
-- Lock the album row first. Two reviews saved at once for the same album
-- then run one after the other, and the second average is computed in a new
-- statement that already sees the first review.
PERFORM 1 FROM album WHERE id = target_album_id FOR UPDATE;

UPDATE album
SET average_rating = (
SELECT avg(rating) FROM review WHERE review.album_id = target_album_id
)
WHERE id = target_album_id;
END;
$$;
--> statement-breakpoint
CREATE FUNCTION refresh_album_average_rating_from_review()
RETURNS trigger
LANGUAGE plpgsql
AS $$
BEGIN
IF TG_OP <> 'DELETE' THEN
PERFORM refresh_album_average_rating(NEW.album_id);
END IF;

IF TG_OP <> 'INSERT' AND OLD.album_id IS DISTINCT FROM NEW.album_id THEN
PERFORM refresh_album_average_rating(OLD.album_id);
END IF;
RETURN NULL;
END;
$$;
--> statement-breakpoint
CREATE TRIGGER review_refresh_album_average_rating
AFTER INSERT OR UPDATE OF rating, album_id OR DELETE ON review
FOR EACH ROW EXECUTE FUNCTION refresh_album_average_rating_from_review();
--> statement-breakpoint
UPDATE album
SET average_rating = rated.average_rating
FROM (
SELECT album_id, avg(rating) AS average_rating
FROM review
GROUP BY album_id
) AS rated
WHERE album.id = rated.album_id;
Loading