diff --git a/README.md b/README.md
index 18654e9..ada5139 100644
--- a/README.md
+++ b/README.md
@@ -4,8 +4,8 @@ Repository for team IT2810-H26-T19 in IT2810-H26.
**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.
+a personal wantlist ("crate"). Results can be filtered by genre, decade and
+whether an album has reviews.
IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks`.
@@ -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, 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.
+**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.
-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.
+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.
-**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.
+**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.
### 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/rating sorting, facet counts and cursor-based pagination. Everything except the filters and facet counts is exposed in the frontend.
+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.
## Try the application
diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx
index 02eed69..21c3b82 100644
--- a/client/src/App.test.tsx
+++ b/client/src/App.test.tsx
@@ -38,6 +38,9 @@ function mockSearch(
searchAlbums: {
edges: albums.map((node) => ({ cursor: node.id, node })),
totalCount: albums.length,
+ genreFacets: [],
+ decadeFacets: [],
+ reviewedCount: 0,
pageInfo: { hasNextPage: false, endCursor: null },
},
},
@@ -97,6 +100,9 @@ describe('App search', () => {
searchAlbums: {
edges: [],
totalCount: 0,
+ genreFacets: [],
+ decadeFacets: [],
+ reviewedCount: 0,
pageInfo: { hasNextPage: false, endCursor: null },
},
},
@@ -121,6 +127,9 @@ describe('App search', () => {
searchAlbums: {
edges: [{ cursor: '1', node: album }],
totalCount: 1,
+ genreFacets: [],
+ decadeFacets: [],
+ reviewedCount: 0,
pageInfo: { hasNextPage: false, endCursor: '1' },
},
},
@@ -182,6 +191,35 @@ describe('App search', () => {
expect(window.location.search).toBe('?q=Abbey');
});
+ it('filters by a genre from its facet and restarts on the first page', async () => {
+ const rock = { genre: { id: '1', name: 'Rock' }, count: 1 };
+ const unfiltered = mockSearch('Abbey');
+ const filtered = mockSearch('Abbey');
+ filtered.request.variables = {
+ input: { query: 'Abbey', sort: 'RELEVANCE', genreIds: ['1'] },
+ first: 20,
+ after: null,
+ };
+ for (const mock of [unfiltered, filtered]) {
+ const data = (mock.result as { data: SearchAlbumsData }).data;
+ data.searchAlbums.genreFacets = [rock];
+ }
+ renderApp([unfiltered, filtered]);
+ submitSearch('Abbey');
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Filters' }));
+ const checkbox = await screen.findByRole('checkbox', { name: 'Rock 1 albums' });
+ fireEvent.click(checkbox);
+
+ expect(window.location.search).toBe('?q=Abbey&genres=1');
+ await waitFor(() =>
+ expect(screen.getByRole('checkbox', { name: 'Rock 1 albums' })).toBeChecked(),
+ );
+ expect(
+ await screen.findByRole('article', { name: 'Abbey Road' }),
+ ).toBeInTheDocument();
+ });
+
it('returns to an empty discovery page from the main navigation', async () => {
window.history.replaceState({}, '', '/?q=Abbey&sort=TITLE_ASC');
const mock = mockSearch('Abbey');
diff --git a/client/src/App.tsx b/client/src/App.tsx
index b94be3c..e9cd43f 100644
--- a/client/src/App.tsx
+++ b/client/src/App.tsx
@@ -2,6 +2,7 @@
import SearchForm from './components/SearchForm.js';
import ResultsLayout from './components/ResultsLayout.js';
+import FilterPanel from './components/FilterPanel.js';
import { lazy, Suspense } from 'react';
import { useAlbumSearch } from './hooks/useAlbumSearch.js';
@@ -60,6 +61,20 @@ function DiscoveryPage() {
+ {search.hasQuery && (
+
+ )}
({ cursor: node.id, node })),
totalCount: albums.length,
+ genreFacets: [],
+ decadeFacets: [],
+ reviewedCount: 0,
pageInfo: { hasNextPage: false, endCursor: null },
},
},
diff --git a/client/src/api/client.test.ts b/client/src/api/client.test.ts
index cece946..7353d02 100644
--- a/client/src/api/client.test.ts
+++ b/client/src/api/client.test.ts
@@ -33,6 +33,9 @@ function result(ids: string[], endCursor: string, hasNextPage = true): SearchAlb
})),
pageInfo: { endCursor, hasNextPage },
totalCount: 4,
+ genreFacets: [],
+ decadeFacets: [],
+ reviewedCount: 0,
},
};
}
diff --git a/client/src/api/searchAlbums.ts b/client/src/api/searchAlbums.ts
index c0b9966..29775ad 100644
--- a/client/src/api/searchAlbums.ts
+++ b/client/src/api/searchAlbums.ts
@@ -19,6 +19,7 @@ export interface AlbumSearchInput {
query: string;
genreIds?: string[] | null;
decades?: number[] | null;
+ hasReviews?: boolean | null;
sort: AlbumSort;
}
@@ -37,6 +38,19 @@ export interface AlbumConnection {
edges: { cursor: string; node: AlbumSummary }[];
pageInfo: { hasNextPage: boolean; endCursor: string | null };
totalCount: number;
+ genreFacets: GenreFacet[];
+ decadeFacets: DecadeFacet[];
+ reviewedCount: number;
+}
+
+export interface GenreFacet {
+ genre: { id: string; name: string };
+ count: number;
+}
+
+export interface DecadeFacet {
+ decade: number;
+ count: number;
}
export interface SearchAlbumsData {
@@ -50,7 +64,7 @@ export interface SearchAlbumsVariables {
}
// gql parses the operation; TypedDocumentNode describes its variables and selected result fields.
-// Only the search-page projection is requested; details and facets belong to later work.
+// Only the search-page projection is requested; details belong to the album page.
export const SEARCH_ALBUMS: TypedDocumentNode =
gql`
query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {
@@ -75,6 +89,18 @@ export const SEARCH_ALBUMS: TypedDocumentNode[0];
+
+function renderPanel(over: Partial = {}) {
+ const props: Props = {
+ genres: [],
+ decades: [],
+ reviewed: false,
+ genreFacets: [
+ { genre: { id: '4', name: 'Rock' }, count: 7 },
+ { genre: { id: '2', name: 'Jazz' }, count: 0 },
+ ],
+ decadeFacets: [
+ { decade: 1970, count: 3 },
+ { decade: 1990, count: 0 },
+ ],
+ reviewedCount: 2,
+ onGenresChange: vi.fn(),
+ onDecadesChange: vi.fn(),
+ onReviewedChange: vi.fn(),
+ onClear: vi.fn(),
+ ...over,
+ };
+ return { props, ...render() };
+}
+
+describe('FilterPanel', () => {
+ it('shows each option with its count', () => {
+ renderPanel();
+ expect(screen.getByRole('checkbox', { name: 'Rock 7 albums' })).toBeInTheDocument();
+ expect(screen.getByRole('checkbox', { name: '1970s 3 albums' })).toBeInTheDocument();
+ expect(
+ screen.getByRole('checkbox', { name: 'Has reviews 2 albums' }),
+ ).toBeInTheDocument();
+ });
+
+ it('hides options that would return nothing', () => {
+ renderPanel({ reviewedCount: 0 });
+ expect(screen.queryByRole('checkbox', { name: /Jazz/ })).not.toBeInTheDocument();
+ expect(screen.queryByRole('checkbox', { name: /1990s/ })).not.toBeInTheDocument();
+ expect(screen.queryByRole('group', { name: 'Reviews' })).not.toBeInTheDocument();
+ });
+
+ it('keeps a selected option visible so it can be unticked', () => {
+ renderPanel({ decades: [1990] });
+ expect(screen.getByRole('checkbox', { name: /1990s/ })).toBeChecked();
+ });
+
+ it('adds and removes values from the selection', () => {
+ const { props } = renderPanel({ genres: ['4'] });
+ fireEvent.click(screen.getByRole('checkbox', { name: /Rock/ }));
+ expect(props.onGenresChange).toHaveBeenCalledWith([]);
+ fireEvent.click(screen.getByRole('checkbox', { name: /1970s/ }));
+ expect(props.onDecadesChange).toHaveBeenCalledWith([1970]);
+ fireEvent.click(screen.getByRole('checkbox', { name: /Has reviews/ }));
+ expect(props.onReviewedChange).toHaveBeenCalledWith(true);
+ });
+
+ it('offers Clear filters only while a filter is active', () => {
+ renderPanel();
+ expect(screen.queryByRole('button', { name: 'Clear filters' })).toBeNull();
+ });
+
+ it('clears every filter', () => {
+ const { props } = renderPanel({ reviewed: true });
+ fireEvent.click(screen.getByRole('button', { name: 'Clear filters' }));
+ expect(props.onClear).toHaveBeenCalled();
+ });
+
+ it('toggles the options from the Filters button and counts active filters', () => {
+ renderPanel({ genres: ['4'], reviewed: true });
+ const button = screen.getByRole('button', { name: 'Filters (2)' });
+ expect(button).toHaveAttribute('aria-expanded', 'false');
+ expect(button).toHaveAttribute('aria-controls', 'filter-options');
+ fireEvent.click(button);
+ expect(button).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('closes on Escape and returns focus to the Filters button', () => {
+ renderPanel();
+ const button = screen.getByRole('button', { name: 'Filters' });
+ fireEvent.click(button);
+ fireEvent.keyDown(screen.getByRole('checkbox', { name: /Rock/ }), { key: 'Escape' });
+ expect(button).toHaveAttribute('aria-expanded', 'false');
+ expect(button).toHaveFocus();
+ });
+
+ it('keeps a selected genre the server reports with no matches', () => {
+ // After a new search term, the server lists selected genres with a count of 0.
+ renderPanel({ genres: ['2'] });
+ expect(screen.getByRole('checkbox', { name: 'Jazz 0 albums' })).toBeChecked();
+ });
+
+ it('has no axe violations', async () => {
+ const { container } = renderPanel({ genres: ['4'] });
+ const results = await axe.run(container, {
+ rules: { 'color-contrast': { enabled: false } },
+ });
+ expect(results.violations.map((violation) => violation.id)).toEqual([]);
+ });
+});
diff --git a/client/src/components/FilterPanel.tsx b/client/src/components/FilterPanel.tsx
new file mode 100644
index 0000000..afa0704
--- /dev/null
+++ b/client/src/components/FilterPanel.tsx
@@ -0,0 +1,140 @@
+import './FilterPanel.css';
+
+import { useEffect, useRef, useState } from 'react';
+
+import type { DecadeFacet, GenreFacet } from '../api/searchAlbums.js';
+
+interface Props {
+ genres: string[];
+ decades: number[];
+ reviewed: boolean;
+ genreFacets: GenreFacet[];
+ decadeFacets: DecadeFacet[];
+ reviewedCount: number;
+ onGenresChange: (genres: string[]) => void;
+ onDecadesChange: (decades: number[]) => void;
+ onReviewedChange: (reviewed: boolean) => void;
+ onClear: () => void;
+}
+
+function toggle(list: T[], value: T): T[] {
+ return list.includes(value) ? list.filter((item) => item !== value) : [...list, value];
+}
+
+/**
+ * Filter checkboxes with the server's facet counts. Genres combine with AND, so
+ * a genre's count is what ticking it would leave. Decades combine with OR, so a
+ * decade's count is how many albums it has with the other filters applied.
+ * Options that would give zero results are hidden, so the panel never leads to
+ * an empty page. A selected option always stays, so it can be unticked.
+ *
+ * The options open from a Filters button above the results, so the panel only
+ * takes space while it is in use. Escape closes it and returns focus to the
+ * button. The heading stays for screen readers; the button is what you see.
+ */
+export default function FilterPanel(props: Props) {
+ const genres = props.genreFacets.filter(
+ ({ genre, count }) => count > 0 || props.genres.includes(genre.id),
+ );
+ const decades = props.decadeFacets.filter(
+ ({ decade, count }) => count > 0 || props.decades.includes(decade),
+ );
+ const showReviewed = props.reviewedCount > 0 || props.reviewed;
+ const activeCount =
+ props.genres.length + props.decades.length + (props.reviewed ? 1 : 0);
+ const active = activeCount > 0;
+ const [open, setOpen] = useState(false);
+ const toggleRef = useRef(null);
+
+ useEffect(() => {
+ if (!open) return;
+ const closeOnEscape = (event: KeyboardEvent) => {
+ if (event.key !== 'Escape') return;
+ setOpen(false);
+ toggleRef.current?.focus();
+ };
+ document.addEventListener('keydown', closeOnEscape);
+ return () => document.removeEventListener('keydown', closeOnEscape);
+ }, [open]);
+
+ return (
+
+ );
+}
diff --git a/client/src/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts
index b9d4716..95b2ae7 100644
--- a/client/src/hooks/useAlbumSearch.ts
+++ b/client/src/hooks/useAlbumSearch.ts
@@ -9,32 +9,36 @@ const PAGE_SIZE = 20;
const AUTOMATIC_PAGE_LIMIT = 2;
export function useAlbumSearch() {
- const { state, setQuery, setSort } = useSearchState();
+ const { state, setQuery, setSort, setGenres, setDecades, setReviewed, clearFilters } =
+ useSearchState();
const query = state.q;
const hasQuery = query.length > 0;
const retryInFlight = useRef(false);
const pagesInFlight = useRef(new Set());
- // The URL defines the result set; Apollo keeps its cached pages.
+ // The URL defines the result set; Apollo keeps its cached pages. A filter
+ // change gives a new key below, so paging starts again from page one.
const input = useMemo(
() => ({
query,
sort: state.sort,
genreIds: state.genres.length > 0 ? state.genres : undefined,
decades: state.decades.length > 0 ? state.decades : undefined,
+ hasReviews: state.reviewed || undefined,
}),
- [query, state.sort, state.genres, state.decades],
+ [query, state.sort, state.genres, state.decades, state.reviewed],
);
- const { data, loading, error, refetch, fetchMore, networkStatus } = useQuery(
- SEARCH_ALBUMS,
- hasQuery
- ? {
- variables: { input, first: PAGE_SIZE, after: null },
- fetchPolicy: 'cache-first',
- }
- : skipToken,
- );
+ const { data, previousData, loading, error, refetch, fetchMore, networkStatus } =
+ useQuery(
+ SEARCH_ALBUMS,
+ hasQuery
+ ? {
+ variables: { input, first: PAGE_SIZE, after: null },
+ fetchPolicy: 'cache-first',
+ }
+ : skipToken,
+ );
const key = JSON.stringify(input);
const [pagination, setPagination] = useState({
@@ -172,8 +176,26 @@ export function useAlbumSearch() {
[query, setQuery, retry],
);
+ // Facets come from the last answer while the next one loads, so the filter
+ // panel does not collapse and lose keyboard focus on every click.
+ const facets = (data ?? previousData)?.searchAlbums;
+
return {
query,
+ filters: {
+ genres: state.genres,
+ decades: state.decades,
+ reviewed: state.reviewed,
+ },
+ facets: {
+ genres: hasQuery ? (facets?.genreFacets ?? []) : [],
+ decades: hasQuery ? (facets?.decadeFacets ?? []) : [],
+ reviewedCount: hasQuery ? (facets?.reviewedCount ?? 0) : 0,
+ },
+ setGenres,
+ setDecades,
+ setReviewed,
+ clearFilters,
sort: state.sort,
setSort,
search,
diff --git a/client/src/hooks/useSearchState.test.ts b/client/src/hooks/useSearchState.test.ts
index 7cb1e12..503b157 100644
--- a/client/src/hooks/useSearchState.test.ts
+++ b/client/src/hooks/useSearchState.test.ts
@@ -24,15 +24,23 @@ describe('parseSearchState', () => {
it('reads every parameter', () => {
expect(
- parseSearchState('?q=blue&sort=TITLE_ASC&genres=4,7&decades=1970,1990'),
+ parseSearchState('?q=blue&sort=TITLE_ASC&genres=4,7&decades=1970,1990&reviewed=1'),
).toEqual({
q: 'blue',
sort: 'TITLE_ASC',
genres: ['4', '7'],
decades: [1970, 1990],
+ reviewed: true,
});
});
+ it('only treats reviewed=1 as the reviewed filter', () => {
+ expect(parseSearchState('?reviewed=yes').reviewed).toBe(false);
+ expect(serializeSearchState({ ...EMPTY_SEARCH_STATE, reviewed: true }, '')).toBe(
+ '?reviewed=1',
+ );
+ });
+
it('falls back to the default sort for a value the schema does not accept', () => {
expect(parseSearchState('?sort=YEAR_DESC').sort).toBe(DEFAULT_SORT);
expect(parseSearchState('?sort=').sort).toBe(DEFAULT_SORT);
@@ -95,7 +103,7 @@ describe('serializeSearchState', () => {
it('never writes a value the server would reject', () => {
const out = serializeSearchState(
- { q: ' ', sort: DEFAULT_SORT, genres: ['rock', '4', ''], decades: [1970] },
+ { ...EMPTY_SEARCH_STATE, q: ' ', genres: ['rock', '4', ''], decades: [1970] },
'',
);
expect(out).toBe('?genres=4&decades=1970');
@@ -116,6 +124,7 @@ describe('serializeSearchState', () => {
sort: 'TITLE_ASC' as const,
genres: ['4'],
decades: [1970],
+ reviewed: true,
};
expect(parseSearchState(serializeSearchState(state, ''))).toEqual(state);
});
@@ -149,6 +158,7 @@ describe('useSearchState', () => {
sort: DEFAULT_SORT,
genres: ['4'],
decades: [1970],
+ reviewed: false,
});
expect(window.location.search).toContain('genres=4');
expect(window.location.search).toContain('decades=1970');
@@ -191,6 +201,7 @@ describe('useSearchState', () => {
'decades',
'genres',
'q',
+ 'reviewed',
'sort',
]);
});
diff --git a/client/src/hooks/useSearchState.ts b/client/src/hooks/useSearchState.ts
index 11b1c27..5cc7b3c 100644
--- a/client/src/hooks/useSearchState.ts
+++ b/client/src/hooks/useSearchState.ts
@@ -11,7 +11,7 @@ import { ALBUM_SORTS, type AlbumSort } from '../api/searchAlbums.js';
* control and #13 the filter panel, and both write through here rather than
* inventing their own strings:
*
- * ?q=blue&sort=TITLE_ASC&genres=4&genres=7&decades=1970&decades=1990
+ * ?q=blue&sort=TITLE_ASC&genres=4&genres=7&decades=1970&decades=1990&reviewed=1
*
* Lists are one param per value. Anything at its default is left out of the
* URL, so a plain search is just `?q=blue`. Parameters this hook does not own
@@ -19,7 +19,7 @@ import { ALBUM_SORTS, type AlbumSort } from '../api/searchAlbums.js';
* already shared.
*
* Paging is deliberately absent. #14 owns the cursor, and the contract is that
- * any change to these four values drops it, so the cursor is never written to
+ * any change to these values drops it, so the cursor is never written to
* the URL and never survives a change of input.
*/
export interface SearchState {
@@ -27,6 +27,7 @@ export interface SearchState {
sort: AlbumSort;
genres: string[];
decades: number[];
+ reviewed: boolean;
}
export const DEFAULT_SORT: AlbumSort = 'RELEVANCE';
@@ -36,6 +37,7 @@ export const EMPTY_SEARCH_STATE: SearchState = {
sort: DEFAULT_SORT,
genres: [],
decades: [],
+ reviewed: false,
};
/** Param names. Import these rather than repeating string literals. */
@@ -44,6 +46,7 @@ export const SEARCH_PARAMS = {
sort: 'sort',
genres: 'genres',
decades: 'decades',
+ reviewed: 'reviewed',
} as const;
function isAlbumSort(value: string | null): value is AlbumSort {
@@ -90,6 +93,7 @@ export function parseSearchState(search: string): SearchState {
sort: isAlbumSort(sort) ? sort : DEFAULT_SORT,
genres: parseValues(params, SEARCH_PARAMS.genres).filter(isGenreId),
decades,
+ reviewed: params.get(SEARCH_PARAMS.reviewed) === '1',
};
}
@@ -104,6 +108,7 @@ export function serializeSearchState(state: SearchState, currentSearch: string):
params.delete(SEARCH_PARAMS.sort);
params.delete(SEARCH_PARAMS.genres);
params.delete(SEARCH_PARAMS.decades);
+ params.delete(SEARCH_PARAMS.reviewed);
const q = state.q.trim();
if (q) params.set(SEARCH_PARAMS.q, q);
@@ -116,6 +121,7 @@ export function serializeSearchState(state: SearchState, currentSearch: string):
params.append(SEARCH_PARAMS.genres, genre);
for (const decade of state.decades)
params.append(SEARCH_PARAMS.decades, String(decade));
+ if (state.reviewed) params.set(SEARCH_PARAMS.reviewed, '1');
const query = params.toString();
return query ? `?${query}` : '';
@@ -175,7 +181,7 @@ function writeSearchState(next: SearchState): void {
}
/**
- * The four values that define a result set, plus the setters that keep the URL
+ * The values that define a result set, plus the setters that keep the URL
* in step. Each setter pushes a history entry, so back and forward step through
* the searches the way a user expects.
*/
@@ -194,5 +200,14 @@ export function useSearchState() {
[setSearch],
);
- return { state, setQuery, setSort, setGenres, setDecades };
+ const setReviewed = useCallback(
+ (reviewed: boolean) => setSearch({ reviewed }),
+ [setSearch],
+ );
+ const clearFilters = useCallback(
+ () => setSearch({ genres: [], decades: [], reviewed: false }),
+ [setSearch],
+ );
+
+ return { state, setQuery, setSort, setGenres, setDecades, setReviewed, clearFilters };
}
diff --git a/client/src/pagination.test.tsx b/client/src/pagination.test.tsx
index bb262a2..8f3569b 100644
--- a/client/src/pagination.test.tsx
+++ b/client/src/pagination.test.tsx
@@ -57,6 +57,9 @@ function page(
},
})),
totalCount: 40,
+ genreFacets: [],
+ decadeFacets: [],
+ reviewedCount: 0,
pageInfo: { endCursor: id, hasNextPage },
},
},
@@ -270,6 +273,10 @@ describe('cursor pagination', () => {
const user = userEvent.setup();
screen.getByRole('button', { name: 'Search' }).focus();
+ // The filter panel's Filters button comes before the results.
+ await user.tab();
+ expect(screen.getByRole('button', { name: 'Filters' })).toHaveFocus();
+
await user.tab();
expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveFocus();
diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md
index 70438c8..7cb270d 100644
--- a/docs/AI-USAGE.md
+++ b/docs/AI-USAGE.md
@@ -68,10 +68,13 @@ the part that matters most.
| 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-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 | evenkkl | Claude | #13, filter panel with facet counts. Read the issue and Erik's comments first; Settled the open questions: keep AND within genres (so the genre counts stay as they are), leave countries to #25, add `hasReviews`. Claude added the `hasReviews` filter and `reviewedCount`, the panel that hides zero-count options, URL state for the filters, tests and doc updates. |
| 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. |
+| 2026-10-28 | evenkkl | Claude | #13 review fixes on PR #65: merged main (infinite scroll), resolved conflicts, added a Filters button for small screens and reconciled the README. Even settled the open review questions and updated the issue text. |
+| 2026-10-29 | evenkkl | Claude | #13 second review round on PR #65: merged main (sorting), selected filters stay in the facets, Filters dropdown on all screens, PostgreSQL tests for AND/OR and facet counts, doc wording. Even chose the dropdown layout. |
## Notes
diff --git a/docs/architecture.md b/docs/architecture.md
index a4a1982..17ddcc8 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -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. 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 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.
## 4. DataLoaders against N+1
@@ -134,7 +134,7 @@ in the URL.
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 URL** holds the search term, genres and sort.
+- **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
diff --git a/docs/data-model.md b/docs/data-model.md
index 5e0d84e..be18e74 100644
--- a/docs/data-model.md
+++ b/docs/data-model.md
@@ -66,9 +66,10 @@ travels and what happens when it is missing.
## Search results
-`searchAlbums` accepts one search term, optional genre and decade filters and a sort
-choice. It returns a cursor-based connection so the client can load results in
-pages. The connection also contains the total number of matches and genre
-and decade facet counts for the filter UI.
+`searchAlbums` accepts one search term, optional genre, decade and has-reviews
+filters and a sort choice. It returns a cursor-based connection so the client can load results in
+pages. The connection also contains the total number of matches, genre and
+decade facet counts, and how many matches have reviews, for the filter UI.
-Genres combine with AND, while decades combine with OR. Filtering, sorting and pagination are handled in SQL. See the README for supported sort options and pagination details.
+Genres combine with AND, while decades combine with OR. So a genre count is what
+ticking that genre would leave, and the decade counts ignore the selected decades. Filtering, sorting and pagination are handled in SQL. See the README for supported sort options and pagination details.
diff --git a/schema.graphql b/schema.graphql
index e15f0f6..0edf8c4 100644
--- a/schema.graphql
+++ b/schema.graphql
@@ -70,6 +70,7 @@ type AlbumConnection {
totalCount: Int!
genreFacets: [GenreFacet!]!
decadeFacets: [DecadeFacet!]!
+ reviewedCount: Int!
}
type AlbumEdge {
@@ -138,6 +139,7 @@ input AlbumSearchInput {
query: String!
genreIds: [ID!]
decades: [Int!]
+ hasReviews: Boolean
sort: AlbumSort!
}
diff --git a/server/src/resolvers.ts b/server/src/resolvers.ts
index 3532d4d..4ca9a1a 100644
--- a/server/src/resolvers.ts
+++ b/server/src/resolvers.ts
@@ -7,10 +7,12 @@ import {
afterCursor,
decodeCursor,
encodeCursor,
+ genreFacetQuery,
orderBy,
pageSize,
searchFilter,
sortKey,
+ withSelectedDecades,
type AlbumSearchInput,
} from './search/search.js';
import { removeReview, saveReview, type UpsertReviewInput } from './reviews.js';
@@ -104,9 +106,9 @@ async function reviewsForAlbum(
}
/**
- * searchAlbums runs four queries, all filtered and sorted in SQL so they
- * cover the whole result set: one page of albums, the total count, and the two
- * facet lists. Album artists and genres are then fetched by the loaders, one
+ * searchAlbums runs five queries, all filtered and sorted in SQL so they
+ * cover the whole result set: one page of albums, the total count, the two
+ * facet lists and the reviewed count. Album artists and genres are then fetched by the loaders, one
* query each for the whole page.
*/
async function searchAlbums(db: Db, { input, first, after }: SearchArgs) {
@@ -115,7 +117,7 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) {
const key = sortKey(input);
const afterSql = after ? afterCursor(key, decodeCursor(after, input.sort)) : sql`TRUE`;
- const [page, total, genreFacets, decadeFacets] = await Promise.all([
+ const [page, total, genreFacets, decadeFacets, reviewed] = await Promise.all([
// One extra row tells us whether there is a next page.
db.execute(sql`
SELECT album.id, album.title, album.release_year AS "releaseYear", ${key.expr} AS "sortValue"
@@ -127,15 +129,7 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) {
db.execute<{ count: number }>(sql`
SELECT count(*)::int AS count FROM album WHERE ${filter}
`),
- db.execute<{ id: number; name: string; count: number }>(sql`
- SELECT genre.id, genre.name, count(*)::int AS count
- FROM album
- JOIN album_genre ON album_genre.album_id = album.id
- JOIN genre ON genre.id = album_genre.genre_id
- WHERE ${filter}
- GROUP BY genre.id, genre.name
- ORDER BY count DESC, genre.name
- `),
+ db.execute<{ id: number; name: string; count: number }>(genreFacetQuery(input)),
db.execute<{ decade: number; count: number }>(sql`
SELECT (album.release_year / 10) * 10 AS decade, count(*)::int AS count
FROM album
@@ -143,6 +137,11 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) {
GROUP BY 1
ORDER BY 1
`),
+ db.execute<{ count: number }>(sql`
+ SELECT count(*)::int AS count FROM album
+ WHERE ${searchFilter(input, 'hasReviews')}
+ AND EXISTS (SELECT 1 FROM review WHERE review.album_id = album.id)
+ `),
]);
const rows = page.rows.slice(0, limit);
@@ -159,7 +158,8 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) {
},
totalCount: total.rows[0]?.count ?? 0,
genreFacets: genreFacets.rows.map(({ count, ...g }) => ({ genre: g, count })),
- decadeFacets: decadeFacets.rows,
+ decadeFacets: withSelectedDecades(decadeFacets.rows, input),
+ reviewedCount: reviewed.rows[0]?.count ?? 0,
};
}
diff --git a/server/src/search/facets.postgres.test.ts b/server/src/search/facets.postgres.test.ts
new file mode 100644
index 0000000..0b8b3d1
--- /dev/null
+++ b/server/src/search/facets.postgres.test.ts
@@ -0,0 +1,120 @@
+import { randomUUID } from 'node:crypto';
+import { drizzle } from 'drizzle-orm/node-postgres';
+import pg from 'pg';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { album, albumGenre, appUser, genre, review } from '../db/schema.js';
+import { createLoaders } from '../loaders/index.js';
+import { resolvers } from '../resolvers.js';
+import type { AlbumSearchInput } from './search.js';
+
+// Set TEST_DATABASE_URL to run these tests. Every fixture row carries a random
+// word, so searching for it keeps the stored catalog out of the counts, and the
+// rows are deleted afterwards.
+describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL filters and facets', () => {
+ // One connection, so the resolver's parallel queries also work against a
+ // single-connection test server such as PGlite.
+ const pool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL, max: 1 });
+ const db = drizzle(pool);
+ const word = `facet${Math.random()
+ .toString(36)
+ .replace(/[^a-z]/g, '')}`;
+ const userId = randomUUID();
+ const ids: Record<'rock' | 'pop' | 'jazz', string> = { rock: '', pop: '', jazz: '' };
+
+ // Rock+Pop 1995 (reviewed), Rock 1995, Rock 2005, Pop 2005, Jazz 1975.
+ const albums = [
+ { title: 'One', year: 1995, genres: ['rock', 'pop'], reviewed: true },
+ { title: 'Two', year: 1995, genres: ['rock'], reviewed: false },
+ { title: 'Three', year: 2005, genres: ['rock'], reviewed: false },
+ { title: 'Four', year: 2005, genres: ['pop'], reviewed: false },
+ { title: 'Five', year: 1975, genres: ['jazz'], reviewed: false },
+ ] as const;
+
+ beforeAll(async () => {
+ for (const name of ['rock', 'pop', 'jazz'] as const) {
+ const [row] = await db
+ .insert(genre)
+ .values({ name: `${name} ${word}` })
+ .returning();
+ ids[name] = String(row!.id);
+ }
+ await db.insert(appUser).values({ id: userId, displayName: 'Facet fixture user' });
+ for (const fixture of albums) {
+ const [row] = await db
+ .insert(album)
+ .values({ title: `${fixture.title} ${word}`, releaseYear: fixture.year })
+ .returning();
+ await db
+ .insert(albumGenre)
+ .values(
+ fixture.genres.map((name) => ({ albumId: row!.id, genreId: +ids[name] })),
+ );
+ if (fixture.reviewed) {
+ await db.insert(review).values({ userId, albumId: row!.id, rating: 4 });
+ }
+ }
+ });
+
+ afterAll(async () => {
+ await pool.query('DELETE FROM app_user WHERE id = $1', [userId]);
+ await pool.query('DELETE FROM album WHERE title LIKE $1', [`% ${word}`]);
+ await pool.query('DELETE FROM genre WHERE name LIKE $1', [`% ${word}`]);
+ await pool.end();
+ });
+
+ async function search(filters: Partial = {}) {
+ const ctx = { db, loaders: createLoaders(db, null), userId: null };
+ const input = { query: word, sort: 'TITLE_ASC' as const, ...filters };
+ const result = await resolvers.Query.searchAlbums(
+ undefined,
+ { input, first: 50 },
+ ctx,
+ );
+ return {
+ titles: result.edges.map((edge) => edge.node.title.split(' ')[0]),
+ totalCount: result.totalCount,
+ genres: Object.fromEntries(
+ result.genreFacets.map((f) => [f.genre.name.split(' ')[0], f.count]),
+ ),
+ decades: Object.fromEntries(result.decadeFacets.map((f) => [f.decade, f.count])),
+ reviewedCount: result.reviewedCount,
+ };
+ }
+
+ it('combines genres with AND', async () => {
+ const result = await search({ genreIds: [ids.rock, ids.pop] });
+ expect(result.titles).toEqual(['One']);
+ expect(result.totalCount).toBe(1);
+ });
+
+ it('combines decades with OR', async () => {
+ const result = await search({ decades: [1990, 2000] });
+ expect(result.totalCount).toBe(4);
+ });
+
+ it('counts genres with the selected genres applied', async () => {
+ const result = await search({ genreIds: [ids.rock] });
+ expect(result.genres).toEqual({ rock: 3, pop: 1 });
+ });
+
+ it('counts decades without the selected decades but with the other filters', async () => {
+ const result = await search({ genreIds: [ids.rock], decades: [1990] });
+ expect(result.totalCount).toBe(2);
+ expect(result.decades).toEqual({ 1990: 2, 2000: 1 });
+ expect(result.genres).toEqual({ rock: 2, pop: 1 });
+ });
+
+ it('counts reviewed albums without the reviewed filter', async () => {
+ expect((await search({ genreIds: [ids.rock] })).reviewedCount).toBe(1);
+ const reviewed = await search({ genreIds: [ids.rock], hasReviews: true });
+ expect(reviewed.titles).toEqual(['One']);
+ expect(reviewed.reviewedCount).toBe(1);
+ });
+
+ it('keeps selected filters in the facets when nothing matches them', async () => {
+ const result = await search({ genreIds: [ids.jazz], decades: [1990] });
+ expect(result.totalCount).toBe(0);
+ expect(result.genres).toEqual({ jazz: 0 });
+ expect(result.decades).toEqual({ 1970: 1, 1990: 0 });
+ });
+});
diff --git a/server/src/search/search.test.ts b/server/src/search/search.test.ts
index 1856a6b..a8ba079 100644
--- a/server/src/search/search.test.ts
+++ b/server/src/search/search.test.ts
@@ -9,6 +9,7 @@ import {
pageSize,
searchFilter,
sortKey,
+ withSelectedDecades,
type AlbumSearchInput,
} from './search.js';
@@ -200,6 +201,22 @@ describe('searchFilter', () => {
expect(sql).toContain('album_genre');
});
+ it('keeps only reviewed albums, except when counting them', () => {
+ const filters = input({ genreIds: ['1'], hasReviews: true });
+ expect(render(searchFilter(filters)).sql).toContain('FROM review');
+ const { sql } = render(searchFilter(filters, 'hasReviews'));
+ expect(sql).not.toContain('FROM review');
+ expect(sql).toContain('album_genre');
+ });
+
+ it('lists selected decades that have no matches with a count of 0', () => {
+ const rows = [{ decade: 1970, count: 2 }];
+ expect(withSelectedDecades(rows, input({ decades: [1990, 1970] }))).toEqual([
+ { decade: 1970, count: 2 },
+ { decade: 1990, count: 0 },
+ ]);
+ });
+
it('requires every selected genre (AND)', () => {
const { sql, params } = render(searchFilter(input({ genreIds: ['3', '4'] })));
expect(sql.match(/EXISTS/g)).toHaveLength(2);
diff --git a/server/src/search/search.ts b/server/src/search/search.ts
index 9195cdf..af5cbb2 100644
--- a/server/src/search/search.ts
+++ b/server/src/search/search.ts
@@ -20,6 +20,7 @@ export type AlbumSearchInput = {
query: string;
genreIds?: readonly string[] | null;
decades?: readonly number[] | null;
+ hasReviews?: boolean | null;
sort: AlbumSort;
};
@@ -52,12 +53,16 @@ function parseGenreId(id: string): number {
}
/**
- * WHERE clause for the search. Passing omit = 'decades' drops the decade filter,
- * which is how decade counts are computed: picking the 1990s still shows how
- * many albums each other decade has. Genre counts use the full filter, because
- * genres combine with AND: with Rock picked, "Pop" counts albums that are both.
+ * WHERE clause for the search. Passing omit drops one filter, which is how the
+ * OR-combined counts are computed: picking the 1990s still shows how many
+ * albums each other decade has, and the reviewed count does not depend on the
+ * reviewed checkbox. Genre counts use the full filter, because genres combine
+ * with AND: with Rock picked, "Pop" counts albums that are both.
*/
-export function searchFilter(input: AlbumSearchInput, omit?: 'decades'): SQL {
+export function searchFilter(
+ input: AlbumSearchInput,
+ omit?: 'decades' | 'hasReviews',
+): SQL {
const conditions: SQL[] = [];
const query = input.query.trim();
@@ -84,9 +89,52 @@ export function searchFilter(input: AlbumSearchInput, omit?: 'decades'): SQL {
);
}
+ if (omit !== 'hasReviews' && input.hasReviews) {
+ conditions.push(sql`EXISTS (SELECT 1 FROM review WHERE review.album_id = album.id)`);
+ }
+
return conditions.length ? sql.join(conditions, sql` AND `) : sql`TRUE`;
}
+/**
+ * Genre counts for the filter panel. Selected genres are always listed, with a
+ * count of 0 when nothing matches any more (say after a new search term), so
+ * the panel can still show them and let the user untick them.
+ */
+export function genreFacetQuery(input: AlbumSearchInput): SQL {
+ const counted = sql`
+ SELECT genre.id, genre.name, count(*)::int AS count
+ FROM album
+ JOIN album_genre ON album_genre.album_id = album.id
+ JOIN genre ON genre.id = album_genre.genre_id
+ WHERE ${searchFilter(input)}
+ GROUP BY genre.id, genre.name
+ `;
+ const selected = (input.genreIds ?? []).map((id) => sql`${parseGenreId(id)}`);
+ if (!selected.length) return sql`${counted} ORDER BY count DESC, genre.name`;
+
+ return sql`
+ WITH counted AS (${counted})
+ SELECT id, name, count FROM counted
+ UNION ALL
+ SELECT genre.id, genre.name, 0 FROM genre
+ WHERE genre.id IN (${sql.join(selected, sql`, `)})
+ AND genre.id NOT IN (SELECT id FROM counted)
+ ORDER BY count DESC, name
+ `;
+}
+
+/** Selected decades are always listed too, with 0 when nothing matches. */
+export function withSelectedDecades(
+ rows: { decade: number; count: number }[],
+ input: AlbumSearchInput,
+): { decade: number; count: number }[] {
+ const missing = (input.decades ?? [])
+ .filter((decade) => !rows.some((row) => row.decade === decade))
+ .map((decade) => ({ decade, count: 0 }));
+ return [...rows, ...missing].sort((a, b) => a.decade - b.decade);
+}
+
/**
* What the results are ordered by. Every sort ends with album.id as a
* tiebreaker so the order is total, which keyset paging needs.