From 466e27afc6019baf55b8a13811129aee0a3f3122 Mon Sep 17 00:00:00 2001 From: Even Date: Mon, 26 Oct 2026 19:34:03 +0100 Subject: [PATCH 01/10] feat: #13 hasReviews filter and reviewed count --- schema.graphql | 2 ++ server/src/resolvers.ts | 14 ++++++++++---- server/src/search/search.test.ts | 8 ++++++++ server/src/search/search.ts | 19 ++++++++++++++----- 4 files changed, 34 insertions(+), 9 deletions(-) diff --git a/schema.graphql b/schema.graphql index d7d1719..5117867 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 c35f502..ef67033 100644 --- a/server/src/resolvers.ts +++ b/server/src/resolvers.ts @@ -103,9 +103,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) { @@ -114,7 +114,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" @@ -142,6 +142,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,6 +164,7 @@ 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, + reviewedCount: reviewed.rows[0]?.count ?? 0, }; } diff --git a/server/src/search/search.test.ts b/server/src/search/search.test.ts index c295052..7714241 100644 --- a/server/src/search/search.test.ts +++ b/server/src/search/search.test.ts @@ -122,6 +122,14 @@ 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('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 1ae09c9..3d9040e 100644 --- a/server/src/search/search.ts +++ b/server/src/search/search.ts @@ -14,6 +14,7 @@ export type AlbumSearchInput = { query: string; genreIds?: readonly string[] | null; decades?: readonly number[] | null; + hasReviews?: boolean | null; sort: AlbumSort; }; @@ -46,12 +47,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(); @@ -78,6 +83,10 @@ 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`; } From 391f176fbcbc6d484f5ade71bf402039db8df5e6 Mon Sep 17 00:00:00 2001 From: Even Date: Mon, 26 Oct 2026 19:34:03 +0100 Subject: [PATCH 02/10] feat: #13 filter panel with facet counts --- client/src/App.css | 10 ++ client/src/App.test.tsx | 37 ++++++++ client/src/App.tsx | 20 +++- client/src/a11y.test.tsx | 3 + client/src/api/client.test.ts | 3 + client/src/api/searchAlbums.ts | 28 +++++- client/src/components/FilterPanel.css | 38 ++++++++ client/src/components/FilterPanel.test.tsx | 81 ++++++++++++++++ client/src/components/FilterPanel.tsx | 102 +++++++++++++++++++++ client/src/hooks/useAlbumSearch.ts | 28 +++++- client/src/hooks/useSearchState.test.ts | 15 ++- client/src/hooks/useSearchState.ts | 23 ++++- 12 files changed, 376 insertions(+), 12 deletions(-) create mode 100644 client/src/components/FilterPanel.css create mode 100644 client/src/components/FilterPanel.test.tsx create mode 100644 client/src/components/FilterPanel.tsx diff --git a/client/src/App.css b/client/src/App.css index 936c93b..31f5456 100644 --- a/client/src/App.css +++ b/client/src/App.css @@ -63,6 +63,12 @@ border-top: 1px solid var(--border); padding-top: 1.25rem; } +.catalogue-layout.with-filters { + display: grid; + grid-template-columns: 220px minmax(0, 1fr); + gap: 2rem; + align-items: start; +} .site-footer { text-align: center; border-top: 1px solid var(--border); @@ -71,6 +77,10 @@ color: var(--muted); } @media (max-width: 700px) { + .catalogue-layout.with-filters { + grid-template-columns: minmax(0, 1fr); + gap: 1rem; + } #main { padding-inline: 1rem; } diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index ec47df6..6082611 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -35,6 +35,9 @@ function mockSearch( searchAlbums: { edges: albums.map((node) => ({ cursor: node.id, node })), totalCount: albums.length, + genreFacets: [], + decadeFacets: [], + reviewedCount: 0, pageInfo: { hasNextPage: false, endCursor: null }, }, }, @@ -94,6 +97,9 @@ describe('App search', () => { searchAlbums: { edges: [], totalCount: 0, + genreFacets: [], + decadeFacets: [], + reviewedCount: 0, pageInfo: { hasNextPage: false, endCursor: null }, }, }, @@ -118,6 +124,9 @@ describe('App search', () => { searchAlbums: { edges: [{ cursor: '1', node: album }], totalCount: 1, + genreFacets: [], + decadeFacets: [], + reviewedCount: 0, pageInfo: { hasNextPage: false, endCursor: '1' }, }, }, @@ -179,6 +188,34 @@ 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'); + + 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', () => { window.history.replaceState({}, '', '/?q=Abbey&sort=TITLE_ASC'); renderApp(); diff --git a/client/src/App.tsx b/client/src/App.tsx index 604b836..43b20f7 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'; @@ -59,7 +60,24 @@ function DiscoveryPage() {

Find something worth listening to.

-
+
+ {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 93412c4..72990f1 100644 --- a/client/src/api/client.test.ts +++ b/client/src/api/client.test.ts @@ -32,6 +32,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 eb5a00c..5c71a4d 100644 --- a/client/src/api/searchAlbums.ts +++ b/client/src/api/searchAlbums.ts @@ -16,6 +16,7 @@ export interface AlbumSearchInput { query: string; genreIds?: string[] | null; decades?: number[] | null; + hasReviews?: boolean | null; sort: AlbumSort; } @@ -33,6 +34,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 { @@ -46,7 +60,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) { @@ -70,6 +84,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('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..2527b98 --- /dev/null +++ b/client/src/components/FilterPanel.tsx @@ -0,0 +1,102 @@ +import './FilterPanel.css'; + +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. + */ +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 active = props.genres.length > 0 || props.decades.length > 0 || props.reviewed; + + return ( + + ); +} diff --git a/client/src/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts index 22d248d..1780ce9 100644 --- a/client/src/hooks/useAlbumSearch.ts +++ b/client/src/hooks/useAlbumSearch.ts @@ -8,7 +8,8 @@ import { useSearchState } from './useSearchState.js'; const PAGE_SIZE = 20; export function useAlbumSearch() { - const { state, setQuery } = useSearchState(); + const { state, setQuery, setGenres, setDecades, setReviewed, clearFilters } = + useSearchState(); const query = state.q; const hasQuery = query.length > 0; const retryInFlight = useRef(false); @@ -16,19 +17,20 @@ export function useAlbumSearch() { // The input is derived from the URL rather than held in React state, so a // reload or a shared link searches for the same thing. Any change to it drops // the cursor: `after` is always null here, so #14 can never page across two - // different result sets. + // different result sets, and ticking a filter always starts on 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], ); // Apollo owns server data; the URL owns what was asked for. - const { data, loading, error, refetch, networkStatus } = useQuery( + const { data, previousData, loading, error, refetch, networkStatus } = useQuery( SEARCH_ALBUMS, hasQuery ? { @@ -65,8 +67,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, search, hasQuery, albums: hasQuery ? (data?.searchAlbums.edges.map((edge) => edge.node) ?? []) : [], diff --git a/client/src/hooks/useSearchState.test.ts b/client/src/hooks/useSearchState.test.ts index 561d365..79c4708 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=TITLE_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 }; } From f4782984efd4d31d96b1a487f2cf895ddde1a719 Mon Sep 17 00:00:00 2001 From: Even Date: Mon, 26 Oct 2026 19:34:03 +0100 Subject: [PATCH 03/10] docs: #13 describe filters, facet counts and AI usage --- README.md | 2 +- docs/AI-USAGE.md | 1 + docs/architecture.md | 2 +- docs/data-model.md | 11 ++++++----- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index a19e1e5..59188ff 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,7 @@ The frontend supports searching by album title or artist, committed on Search or ### 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, decade and has-reviews filters, relevance/title/release-year sorting, facet counts and cursor-based pagination. The search page has a filter panel with these counts; sorting and paging controls are not exposed in the frontend yet. ## Try the application diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index c3b744c..1f5bbb7 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -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 | #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. | ## Notes diff --git a/docs/architecture.md b/docs/architecture.md index 91b744d..55a3b82 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. 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. 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. The supported sort options are `RELEVANCE`, `TITLE_ASC` and `RELEASE_YEAR_DESC`; rating-based sorting is not yet implemented. ## 4. DataLoaders against N+1 diff --git a/docs/data-model.md b/docs/data-model.md index 7cc88e5..b559a87 100644 --- a/docs/data-model.md +++ b/docs/data-model.md @@ -47,9 +47,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. From 443daab9e69ec3ef193a69e5761745e2a3b1e57a Mon Sep 17 00:00:00 2001 From: Even Date: Mon, 26 Oct 2026 19:55:18 +0100 Subject: [PATCH 04/10] style: #13 format AI usage log --- docs/AI-USAGE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index 1f5bbb7..578bbd7 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -65,7 +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 | #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 | 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. | ## Notes From c1781ba0515c821103af4bb485807ec23c874dab Mon Sep 17 00:00:00 2001 From: Even Date: Wed, 28 Oct 2026 18:19:49 +0100 Subject: [PATCH 05/10] fix: #13 filter button on small screens --- client/src/components/FilterPanel.css | 28 +++++ client/src/components/FilterPanel.test.tsx | 9 ++ client/src/components/FilterPanel.tsx | 128 ++++++++++++--------- client/src/pagination.test.tsx | 4 + 4 files changed, 116 insertions(+), 53 deletions(-) diff --git a/client/src/components/FilterPanel.css b/client/src/components/FilterPanel.css index 616ad6c..0c8b0d4 100644 --- a/client/src/components/FilterPanel.css +++ b/client/src/components/FilterPanel.css @@ -36,3 +36,31 @@ color: var(--text); border: 1px solid var(--border-strong); } +.filter-toggle { + display: none; + width: 100%; + background: var(--surface); + color: var(--text); + border: 1px solid var(--border-strong); + text-align: left; +} +@media (max-width: 700px) { + /* The button names the panel here, so the heading is kept for screen readers only. */ + .filter-panel h2 { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + } + .filter-toggle { + display: block; + } + .filter-options:not(.open) { + display: none; + } + .filter-options.open { + padding-top: 0.75rem; + } +} diff --git a/client/src/components/FilterPanel.test.tsx b/client/src/components/FilterPanel.test.tsx index 64d215e..0098013 100644 --- a/client/src/components/FilterPanel.test.tsx +++ b/client/src/components/FilterPanel.test.tsx @@ -71,6 +71,15 @@ describe('FilterPanel', () => { 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('has no axe violations', async () => { const { container } = renderPanel({ genres: ['4'] }); const results = await axe.run(container, { diff --git a/client/src/components/FilterPanel.tsx b/client/src/components/FilterPanel.tsx index 2527b98..448b3a6 100644 --- a/client/src/components/FilterPanel.tsx +++ b/client/src/components/FilterPanel.tsx @@ -1,5 +1,7 @@ import './FilterPanel.css'; +import { useState } from 'react'; + import type { DecadeFacet, GenreFacet } from '../api/searchAlbums.js'; interface Props { @@ -25,6 +27,9 @@ function toggle(list: T[], value: T): T[] { * 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. + * + * On small screens the options sit behind a Filters button so the results stay + * in view; on wider screens the button is hidden and the options always show. */ export default function FilterPanel(props: Props) { const genres = props.genreFacets.filter( @@ -34,69 +39,86 @@ export default function FilterPanel(props: Props) { ({ decade, count }) => count > 0 || props.decades.includes(decade), ); const showReviewed = props.reviewedCount > 0 || props.reviewed; - const active = props.genres.length > 0 || props.decades.length > 0 || props.reviewed; + const activeCount = + props.genres.length + props.decades.length + (props.reviewed ? 1 : 0); + const active = activeCount > 0; + const [open, setOpen] = useState(false); return (
); } diff --git a/client/src/pagination.test.tsx b/client/src/pagination.test.tsx index 6d5fe37..f9063b2 100644 --- a/client/src/pagination.test.tsx +++ b/client/src/pagination.test.tsx @@ -273,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('link', { name: 'Album 1' })).toHaveFocus(); From 9e9b5375677d656d403e0e1a683ab4f18d255c9a Mon Sep 17 00:00:00 2001 From: Even Date: Wed, 28 Oct 2026 18:19:50 +0100 Subject: [PATCH 06/10] docs: #13 reconcile README with pagination --- README.md | 12 ++++++------ docs/AI-USAGE.md | 1 + 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 3f4c0bc..f6431cc 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,8 @@ 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 +supports filtering, sorting and cursor-based pagination. The frontend has the +filter panel and paging, while sorting controls are planned. Album details, ratings, reviews and a personal wantlist ("crate") are also planned. 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. 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, decade and has-reviews filters with facet counts, 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. -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. 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 filter panel narrows the results by genre, decade and whether an album has reviews. Each option shows how many albums it would leave, options with no matches are hidden, and on small screens the panel opens from a Filters button. Changing a filter starts again from the first 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 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. ### 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 sorting, facet counts and cursor-based pagination. The search page has a filter panel with these counts; sorting and paging controls are not 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, decade and has-reviews filters, relevance/title/release-year sorting, facet counts and cursor-based pagination. The search page exposes the filters, facet counts and paging; sorting controls are not exposed in the frontend yet. ## Try the application diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index d30baae..4557346 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -71,6 +71,7 @@ the part that matters most. | 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-27 | robertky | Codex (ChatGPT) | Assisted me with #63's MusicBrainz snapshot fetcher, non-destructive catalog import and documentation. | +| 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. | ## Notes From 9639a76cd2a66287a2311e81f15499befe761a59 Mon Sep 17 00:00:00 2001 From: Even Date: Thu, 29 Oct 2026 15:54:00 +0100 Subject: [PATCH 07/10] fix: #13 keep selected filters in facets --- client/src/components/FilterPanel.test.tsx | 6 ++++ server/src/resolvers.ts | 14 +++----- server/src/search/search.test.ts | 9 +++++ server/src/search/search.ts | 39 ++++++++++++++++++++++ 4 files changed, 58 insertions(+), 10 deletions(-) diff --git a/client/src/components/FilterPanel.test.tsx b/client/src/components/FilterPanel.test.tsx index 0098013..59bf661 100644 --- a/client/src/components/FilterPanel.test.tsx +++ b/client/src/components/FilterPanel.test.tsx @@ -80,6 +80,12 @@ describe('FilterPanel', () => { expect(button).toHaveAttribute('aria-expanded', 'true'); }); + 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, { diff --git a/server/src/resolvers.ts b/server/src/resolvers.ts index c7c0390..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'; @@ -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 @@ -164,7 +158,7 @@ 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/search.test.ts b/server/src/search/search.test.ts index 14fd6e2..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'; @@ -208,6 +209,14 @@ describe('searchFilter', () => { 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 6fee91b..af5cbb2 100644 --- a/server/src/search/search.ts +++ b/server/src/search/search.ts @@ -96,6 +96,45 @@ export function searchFilter( 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. From 6061a5a33b4b4986e4d914e134c664cf2550403d Mon Sep 17 00:00:00 2001 From: Even Date: Thu, 29 Oct 2026 15:54:01 +0100 Subject: [PATCH 08/10] feat: #13 filters dropdown on all screens --- client/src/App.css | 10 ---- client/src/App.test.tsx | 1 + client/src/App.tsx | 5 +- client/src/components/FilterPanel.css | 53 ++++++++++------------ client/src/components/FilterPanel.test.tsx | 9 ++++ client/src/components/FilterPanel.tsx | 24 ++++++++-- 6 files changed, 56 insertions(+), 46 deletions(-) diff --git a/client/src/App.css b/client/src/App.css index 31f5456..936c93b 100644 --- a/client/src/App.css +++ b/client/src/App.css @@ -63,12 +63,6 @@ border-top: 1px solid var(--border); padding-top: 1.25rem; } -.catalogue-layout.with-filters { - display: grid; - grid-template-columns: 220px minmax(0, 1fr); - gap: 2rem; - align-items: start; -} .site-footer { text-align: center; border-top: 1px solid var(--border); @@ -77,10 +71,6 @@ color: var(--muted); } @media (max-width: 700px) { - .catalogue-layout.with-filters { - grid-template-columns: minmax(0, 1fr); - gap: 1rem; - } #main { padding-inline: 1rem; } diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index b3cb1ac..21c3b82 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -207,6 +207,7 @@ describe('App search', () => { 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); diff --git a/client/src/App.tsx b/client/src/App.tsx index 0ccc617..e9cd43f 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -60,10 +60,7 @@ function DiscoveryPage() {

Find something worth listening to.

-
+
{search.hasQuery && ( { 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'] }); diff --git a/client/src/components/FilterPanel.tsx b/client/src/components/FilterPanel.tsx index 448b3a6..afa0704 100644 --- a/client/src/components/FilterPanel.tsx +++ b/client/src/components/FilterPanel.tsx @@ -1,6 +1,6 @@ import './FilterPanel.css'; -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import type { DecadeFacet, GenreFacet } from '../api/searchAlbums.js'; @@ -28,8 +28,9 @@ function toggle(list: T[], value: T): T[] { * 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. * - * On small screens the options sit behind a Filters button so the results stay - * in view; on wider screens the button is hidden and the options always show. + * 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( @@ -43,11 +44,26 @@ export default function FilterPanel(props: Props) { 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 (