diff --git a/client/src/App.css b/client/src/App.css index e9bd5ab..9ea730d 100644 --- a/client/src/App.css +++ b/client/src/App.css @@ -19,6 +19,7 @@ margin: auto; padding: 1rem 2rem; display: flex; + flex-wrap: wrap; align-items: center; gap: 2.5rem; } @@ -30,6 +31,7 @@ padding-block: 0.4rem; } .brand { + font-family: var(--font-display); font-size: 1.8rem; font-weight: 800; letter-spacing: -0.08rem; @@ -44,20 +46,98 @@ padding-inline: 2rem; margin: auto; } +/* Full-bleed hero; keep the existing catalogue content width and navigation. */ +#main.discovery-main { + max-width: none; + padding-inline: 0; +} +.discovery-main > .catalogue-layout { + width: min(100% - 4rem, 1176px); + margin-inline: auto; +} .search-section { - text-align: center; - padding: 2.5rem 0 2rem; + --bg: var(--header-bg); + --text: var(--header-text); + --accent: var(--header-accent); + --accent-hover: #adf4cc; + --accent-text: var(--header-bg); + --muted: #c0c9c1; + --surface: #111914; + --border-strong: #8caa97; + --focus: var(--header-accent); + color-scheme: dark; + position: relative; + isolation: isolate; + display: flex; + align-items: center; + min-height: 31.25rem; + padding-block: 3rem 2rem; + background: var(--bg); + color: var(--text); +} +.search-section::before, +.search-section::after { + content: ''; + position: absolute; + inset: 0; + pointer-events: none; +} +.search-section::before { + z-index: -2; + background: url('./assets/vinyl-hero.webp') center 22% / cover; + filter: saturate(0.5) contrast(1.03); +} +.search-section::after { + z-index: -1; + background: + linear-gradient( + 90deg, + rgba(5, 12, 8, 0.97), + rgba(5, 12, 8, 0.9) 34%, + rgba(5, 12, 8, 0.36) max(72%, 45rem), + rgba(5, 12, 8, 0.18) + ), + linear-gradient(0deg, var(--bg), transparent 24%); +} +.search-section__content { + width: 100%; + max-width: 1240px; + margin-inline: auto; + padding-inline: 2rem; + min-width: 0; +} +.search-section .eyebrow { + margin-bottom: 1.125rem; + letter-spacing: 0.18em; } .search-section h1 { margin: 0; - font-size: clamp(2rem, 4.5vw, 3.5rem); - font-weight: 750; + font-size: clamp(3rem, 6.3vw, 5.5rem); + font-weight: 700; letter-spacing: -0.055em; - line-height: 1.15; + line-height: 1.05; + overflow-wrap: anywhere; +} +.search-section h1 em { + color: var(--accent-hover); + font-family: Georgia, serif; + font-weight: 400; +} +.search-section .tagline { + max-width: 42.5rem; + color: var(--muted); + font-size: 1.125rem; + margin: 1.5rem 0 1.875rem; } -.tagline { +.hero-credit { + margin: 2rem 0 0; color: var(--muted); - margin: 1rem 0 1.7rem; + font-size: 0.75rem; +} +.hero-credit a { + display: inline-block; + padding-block: 0.25rem; + text-underline-offset: 0.2em; } .catalogue-layout { border-top: 1px solid var(--border); @@ -70,6 +150,17 @@ font-size: 0.8rem; color: var(--muted); } +@media (prefers-color-scheme: light) { + .discovery-main .album-card { + background: var(--surface); + border-radius: 3px; + /* An inset border preserves the card and artwork dimensions. */ + box-shadow: inset 0 0 0 1px var(--border); + } + .discovery-main .album-card__cover { + background: var(--border); + } +} @media (max-width: 700px) { #main { padding-inline: 1rem; @@ -78,8 +169,33 @@ padding: 1rem; gap: 1.5rem; } + .discovery-main > .catalogue-layout { + width: calc(100% - 2rem); + } .search-section { - padding-block: 2rem; + min-height: 0; + align-items: end; + padding-block: 2.5rem 2rem; + } + .search-section__content { + padding-inline: 1rem; + } + .search-section::before { + background-position: center 24%; + } + .search-section::after { + background: linear-gradient( + 0deg, + var(--bg), + rgba(5, 12, 8, 0.78) 72%, + rgba(5, 12, 8, 0.65) + ); + } + .search-section h1 { + font-size: clamp(2.5rem, 8vw, 3rem); + } + .search-section .tagline { + font-size: 1rem; } } @media (max-width: 420px) { diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index 21c3b82..2375df5 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -4,6 +4,7 @@ import { MockedProvider } from '@apollo/client/testing/react'; import type { MockLink } from '@apollo/client/testing'; import { GraphQLError } from 'graphql'; import App from './App.js'; +import userEvent from '@testing-library/user-event'; import { SEARCH_ALBUMS } from './api/searchAlbums.js'; import type { AlbumSort, @@ -26,7 +27,7 @@ const album: AlbumSummary = { function mockSearch( query: string, albums: AlbumSummary[] = [album], - sort: AlbumSort = 'RELEVANCE', + sort: AlbumSort = query.trim() ? 'RELEVANCE' : 'RELEASE_YEAR_DESC', ): MockLink.MockedResponse { return { request: { @@ -46,6 +47,7 @@ function mockSearch( }, }, delay: 10, + maxUsageCount: query === '' ? Number.POSITIVE_INFINITY : 1, }; } @@ -53,7 +55,17 @@ function renderApp( mocks: MockLink.MockedResponse[] = [], ) { return render( - + + typeof mock.request.variables !== 'function' && + mock.request.variables?.input.query === '', + ) + ? mocks + : [mockSearch('', []), ...mocks] + } + > , ); @@ -65,6 +77,230 @@ function submitSearch(query: string) { } describe('App search', () => { + it('loads a filter-only URL and sorts browsing results on the server', async () => { + window.history.replaceState({}, '', '/?genres=1&decades=1960&reviewed=1'); + const filtered = mockSearch(''); + filtered.request.variables = { + input: { + query: '', + sort: 'RELEASE_YEAR_DESC', + genreIds: ['1'], + decades: [1960], + hasReviews: true, + }, + first: 20, + after: null, + }; + const sorted = mockSearch('', [album], 'TITLE_DESC'); + sorted.request.variables = { + ...filtered.request.variables, + input: { ...filtered.request.variables.input, sort: 'TITLE_DESC' }, + }; + renderApp([filtered, sorted]); + await screen.findByRole('article', { name: 'Abbey Road' }); + fireEvent.change(screen.getByRole('combobox', { name: 'Sort by' }), { + target: { value: 'TITLE_DESC' }, + }); + await waitFor(() => + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 1 of 1 matching albums.', + ), + ); + expect(window.location.search).toBe( + '?sort=TITLE_DESC&genres=1&decades=1960&reviewed=1', + ); + }); + + it.each(['', 'Abbey'])( + 'clears filters while preserving query %j, sort and browser history', + async (query) => { + const url = '/?q=' + query + '&sort=TITLE_DESC&genres=1&decades=1960&reviewed=1'; + window.history.replaceState({}, '', url); + const filtered = mockSearch(query, [album], 'TITLE_DESC'); + filtered.request.variables = { + input: { + query, + sort: 'TITLE_DESC', + genreIds: ['1'], + decades: [1960], + hasReviews: true, + }, + first: 20, + after: null, + }; + const unfiltered = mockSearch(query, [album], 'TITLE_DESC'); + for (const mock of [filtered, unfiltered]) { + const data = (mock.result as { data: SearchAlbumsData }).data; + data.searchAlbums.genreFacets = [{ genre: { id: '1', name: 'Rock' }, count: 1 }]; + data.searchAlbums.decadeFacets = [{ decade: 1960, count: 1 }]; + data.searchAlbums.reviewedCount = 1; + } + renderApp([filtered, unfiltered]); + await screen.findByRole('article', { name: 'Abbey Road' }); + fireEvent.click(screen.getByRole('button', { name: 'Filters (3)' })); + expect(screen.getByRole('checkbox', { name: 'Rock 1 albums' })).toBeChecked(); + const clear = screen.getByRole('button', { name: 'Clear filters' }); + clear.focus(); + fireEvent.click(clear); + expect(clear).toHaveFocus(); + expect(clear).toHaveAttribute('aria-disabled', 'true'); + expect(window.location.search).toBe( + query ? '?q=Abbey&sort=TITLE_DESC' : '?sort=TITLE_DESC', + ); + expect( + screen.queryByRole('list', { name: 'Active filters' }), + ).not.toBeInTheDocument(); + await screen.findByRole('article', { name: 'Abbey Road' }); + await act(async () => { + window.history.back(); + }); + await waitFor(() => + expect(screen.getByRole('checkbox', { name: 'Rock 1 albums' })).toBeChecked(), + ); + expect(screen.getByRole('list', { name: 'Active filters' })).toHaveTextContent( + 'Rock', + ); + await act(async () => { + window.history.forward(); + }); + await waitFor(() => + expect(screen.getByRole('checkbox', { name: 'Rock 1 albums' })).not.toBeChecked(), + ); + expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue('TITLE_DESC'); + }, + ); + + it('removes a decade chip through URL state while retaining query, other filters and sort', async () => { + window.history.replaceState( + {}, + '', + '/?q=Abbey&sort=TITLE_DESC&genres=1&decades=1960&reviewed=1', + ); + const filtered = mockSearch('Abbey', [album], 'TITLE_DESC'); + filtered.request.variables = { + input: { + query: 'Abbey', + sort: 'TITLE_DESC', + genreIds: ['1'], + decades: [1960], + hasReviews: true, + }, + first: 20, + after: null, + }; + const withoutDecade = mockSearch('Abbey', [album], 'TITLE_DESC'); + withoutDecade.request.variables = { + input: { query: 'Abbey', sort: 'TITLE_DESC', genreIds: ['1'], hasReviews: true }, + first: 20, + after: null, + }; + renderApp([filtered, withoutDecade]); + await screen.findByRole('article', { name: 'Abbey Road' }); + fireEvent.click(screen.getByRole('button', { name: 'Remove decade filter: 1960s' })); + expect(window.location.search).toBe('?q=Abbey&sort=TITLE_DESC&genres=1&reviewed=1'); + expect( + screen.queryByRole('button', { name: 'Remove decade filter: 1960s' }), + ).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Filters (2)' })).toHaveFocus(); + await waitFor(() => + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 1 of 1 matching albums.', + ), + ); + expect(screen.getByRole('searchbox')).toHaveValue('Abbey'); + expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue('TITLE_DESC'); + }); + + it('formats the loaded and total matching counts', async () => { + const mock = mockSearch( + '', + Array.from({ length: 20 }, (_, i) => ({ ...album, id: String(i + 1) })), + ); + (mock.result as { data: SearchAlbumsData }).data.searchAlbums.totalCount = 100500; + renderApp([mock]); + await waitFor(() => + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 20 of 100,500 matching albums.', + ), + ); + }); + + it('filters a search from the first page and retains keyboard focus as facets and URL change', async () => { + const unfiltered = mockSearch('Abbey', [ + album, + { ...album, id: '2', title: 'Other album' }, + ]); + const filtered = mockSearch('Abbey'); + filtered.request.variables = { + input: { query: 'Abbey', sort: 'RELEVANCE', genreIds: ['1'] }, + first: 20, + after: null, + }; + for (const [mock, count] of [ + [unfiltered, 2], + [filtered, 1], + ] as const) { + (mock.result as { data: SearchAlbumsData }).data.searchAlbums.genreFacets = [ + { genre: { id: '1', name: 'Rock' }, count }, + ...(count === 2 ? [{ genre: { id: '2', name: 'Other genre' }, count: 1 }] : []), + ]; + } + renderApp([unfiltered, filtered]); + submitSearch('Abbey'); + await screen.findByRole('article', { name: 'Other album' }); + const user = userEvent.setup(); + screen.getByRole('button', { name: 'Filters' }).focus(); + await user.keyboard('{Enter}'); + await user.tab(); + expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveFocus(); + await user.tab(); + expect(screen.getByRole('button', { name: 'Clear filters' })).toHaveFocus(); + await user.tab(); + const rock = screen.getByRole('checkbox', { name: 'Rock 2 albums' }); + expect(rock).toHaveFocus(); + await user.keyboard(' '); + await waitFor(() => + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 1 of 1 matching albums.', + ), + ); + expect(window.location.search).toBe('?q=Abbey&genres=1'); + expect(screen.getByRole('checkbox', { name: 'Rock 1 albums' })).toBeChecked(); + expect(rock).toHaveFocus(); + expect( + screen.getByRole('button', { name: 'Remove genre filter: Rock' }), + ).toBeInTheDocument(); + expect( + screen.queryByRole('checkbox', { name: 'Other genre 1 albums' }), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole('article', { name: 'Other album' }), + ).not.toBeInTheDocument(); + await user.keyboard(' '); + await waitFor(() => + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 2 of 2 matching albums.', + ), + ); + expect(window.location.search).toBe('?q=Abbey'); + expect(rock).toHaveFocus(); + }); + + it('retries a failed initial browse request', async () => { + renderApp([ + { + ...mockSearch(''), + result: undefined, + error: new Error('Offline'), + maxUsageCount: 1, + }, + mockSearch(''), + ]); + await screen.findByRole('alert'); + fireEvent.click(screen.getByRole('button', { name: 'Retry albums' })); + await screen.findByRole('article', { name: 'Abbey Road' }); + }); + it.each(['Enter', 'Search button'])( 'retries a failed query through %s', async (method) => { @@ -160,19 +396,29 @@ describe('App search', () => { expect(result).toHaveBeenCalledTimes(1); }); - it('starts with labelled search and accessible landmarks, hiding pagination until results exist', () => { - renderApp(); + it('loads albums initially with labelled search and accessible landmarks', async () => { + renderApp([mockSearch('')]); expect( screen.getByRole('searchbox', { name: 'Search by album or artist' }), ).toHaveValue(''); expect(screen.getByRole('main')).toHaveAttribute('id', 'main'); + const hero = screen.getByRole('region', { name: 'Music worth holding onto.' }); + expect( + within(hero).getByText('Search, rate and collect albums you’ll want to return to.'), + ).toBeInTheDocument(); + expect(within(hero).getByRole('search')).toBeInTheDocument(); expect(document.querySelector('a')).toBe( screen.getByRole('link', { name: 'Skip to content' }), ); - expect(screen.getByRole('status')).toHaveTextContent('Search for an album or artist'); - expect(screen.queryByRole('combobox')).not.toBeInTheDocument(); + expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue( + 'RELEASE_YEAR_DESC', + ); + expect(screen.getByRole('status')).toHaveTextContent('Loading albums'); + expect(screen.getByRole('combobox', { name: 'Sort by' })).toBeInTheDocument(); expect(screen.queryByRole('checkbox')).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument(); + await screen.findByRole('article', { name: 'Abbey Road' }); + expect(screen.getByRole('region', { name: 'Browse albums' })).toBeInTheDocument(); }); it('writes the query to the URL on submission and not while typing', async () => { @@ -191,36 +437,7 @@ 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 () => { + it('links to unfiltered browsing from the main navigation', async () => { window.history.replaceState({}, '', '/?q=Abbey&sort=TITLE_ASC'); const mock = mockSearch('Abbey'); mock.request.variables = { @@ -238,17 +455,11 @@ describe('App search', () => { }); it('treats a pasted whitespace-only query as no query at all', async () => { - // Without trimming on parse this counted as an active search and went to - // the backend, which trimmed it to nothing and returned an empty result. window.history.replaceState({}, '', '/?q=%20%20'); - renderApp([mockSearch('Abbey')]); - + renderApp([mockSearch('')]); expect(screen.getByRole('searchbox')).toHaveValue(''); - expect(screen.getByRole('status')).toHaveTextContent('Search for an album or artist'); - expect(screen.queryByText('Searching albums…')).not.toBeInTheDocument(); - expect(screen.queryByText('No albums found')).not.toBeInTheDocument(); - await act(() => new Promise((resolve) => setTimeout(resolve, 150))); - expect(screen.getByRole('status')).toHaveTextContent('Search for an album or artist'); + await screen.findByRole('article', { name: 'Abbey Road' }); + expect(screen.getByRole('region', { name: 'Browse albums' })).toBeInTheDocument(); }); it('shows loading and then renders GraphQL result metadata after submission', async () => { @@ -267,20 +478,42 @@ describe('App search', () => { expect(within(card).getByText('Rock')).toBeInTheDocument(); expect(within(card).getByText('1,240 reviews')).toBeInTheDocument(); expect(card).toHaveTextContent('Average rating: 4.8 out of 5'); - expect(screen.getByRole('status')).toHaveTextContent('Showing 1 of 1 albums.'); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 1 of 1 matching albums.', + ); }); - it('shows an empty result and clears the query without querying fixtures', async () => { - renderApp([mockSearch('missing', [])]); - submitSearch('missing'); - expect( - await screen.findByRole('heading', { name: 'No albums found' }), - ).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Clear search' })); - expect(screen.getByRole('searchbox')).toHaveValue(''); - expect(screen.getByRole('status')).toHaveTextContent('Search for an album or artist'); - expect(screen.queryByRole('article')).not.toBeInTheDocument(); - }); + it.each(['missing', ''])( + 'resets zero results for query %j and all filters while preserving sort', + async (query) => { + window.history.replaceState( + {}, + '', + '/?q=' + query + '&sort=TITLE_DESC&genres=1&decades=1960&reviewed=1', + ); + const empty = mockSearch(query, [], 'TITLE_DESC'); + empty.request.variables = { + input: { + query, + sort: 'TITLE_DESC', + genreIds: ['1'], + decades: [1960], + hasReviews: true, + }, + first: 20, + after: null, + }; + renderApp([empty, mockSearch('', [album], 'TITLE_DESC')]); + await screen.findByRole('heading', { name: 'No albums found' }); + fireEvent.click(screen.getByRole('button', { name: 'Reset search' })); + expect(screen.getByRole('searchbox')).toHaveValue(''); + expect(window.location.search).toBe('?sort=TITLE_DESC'); + expect(screen.getByRole('button', { name: 'Filters' })).toBeInTheDocument(); + expect(screen.getByRole('combobox', { name: 'Sort by' })).toHaveValue('TITLE_DESC'); + await screen.findByRole('article', { name: 'Abbey Road' }); + expect(screen.getByRole('region', { name: 'Browse albums' })).toBeInTheDocument(); + }, + ); it('shows network errors and retries the same search', async () => { const failed = { @@ -318,7 +551,9 @@ describe('App search', () => { await screen.findByRole('article', { name: 'Abbey Road' }), ).toBeInTheDocument(); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); - expect(screen.getByRole('status')).toHaveTextContent('Showing 1 of 1 albums.'); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 1 of 1 matching albums.', + ); }); it('re-queries the server when the sort changes and keeps it in the URL', async () => { diff --git a/client/src/App.tsx b/client/src/App.tsx index e9cd43f..fbea3cb 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -2,7 +2,6 @@ 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'; @@ -53,29 +52,40 @@ function DiscoveryPage() { const search = useAlbumSearch(); return ( -
+
-

A world of records

-

Discover your next album.

-

Find something worth listening to.

- +
+

Your next favorite is in here

+

+ Music worth +
holding onto. +

+

+ Search, rate and collect albums you’ll want to return to. +

+ +

+ Photo by{' '} + + Kevin McCutcheon on Unsplash + +

+
- {search.hasQuery && ( - - )} search.search('')} + onReset={search.resetSearch} />
diff --git a/client/src/a11y.test.tsx b/client/src/a11y.test.tsx index 64fd69a..15bff44 100644 --- a/client/src/a11y.test.tsx +++ b/client/src/a11y.test.tsx @@ -32,7 +32,11 @@ function mockSearch( return { request: { query: SEARCH_ALBUMS, - variables: { input: { query, sort: 'RELEVANCE' }, first: 20, after: null }, + variables: { + input: { query, sort: query.trim() ? 'RELEVANCE' : 'RELEASE_YEAR_DESC' }, + first: 20, + after: null, + }, }, result: { data: { @@ -54,7 +58,7 @@ function renderApp( mocks: MockLink.MockedResponse[] = [], ) { return render( - + , ); @@ -104,7 +108,7 @@ describe('axe-core on the search page', () => { await screen.findByRole('region', { name: 'Search results' }); await waitFor(() => - expect(screen.getByText(/Showing 1 of 1 albums/)).toBeInTheDocument(), + expect(screen.getByText(/Showing 1 of 1 matching albums/)).toBeInTheDocument(), ); await expectNoViolations(container); diff --git a/client/src/assets/fonts/DM-Sans-OFL.txt b/client/src/assets/fonts/DM-Sans-OFL.txt new file mode 100644 index 0000000..a0eedfb --- /dev/null +++ b/client/src/assets/fonts/DM-Sans-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2014 The DM Sans Project Authors (https://github.com/googlefonts/dm-fonts) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/client/src/assets/fonts/Manrope-OFL.txt b/client/src/assets/fonts/Manrope-OFL.txt new file mode 100644 index 0000000..793d053 --- /dev/null +++ b/client/src/assets/fonts/Manrope-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2018 The Manrope Project Authors (https://github.com/googlefonts/manrope) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/client/src/assets/fonts/dm-sans-latin-ext.woff2 b/client/src/assets/fonts/dm-sans-latin-ext.woff2 new file mode 100644 index 0000000..db39c62 Binary files /dev/null and b/client/src/assets/fonts/dm-sans-latin-ext.woff2 differ diff --git a/client/src/assets/fonts/dm-sans-latin.woff2 b/client/src/assets/fonts/dm-sans-latin.woff2 new file mode 100644 index 0000000..01383d7 Binary files /dev/null and b/client/src/assets/fonts/dm-sans-latin.woff2 differ diff --git a/client/src/assets/fonts/manrope-latin-ext.woff2 b/client/src/assets/fonts/manrope-latin-ext.woff2 new file mode 100644 index 0000000..e756446 Binary files /dev/null and b/client/src/assets/fonts/manrope-latin-ext.woff2 differ diff --git a/client/src/assets/fonts/manrope-latin.woff2 b/client/src/assets/fonts/manrope-latin.woff2 new file mode 100644 index 0000000..f3122c1 Binary files /dev/null and b/client/src/assets/fonts/manrope-latin.woff2 differ diff --git a/client/src/assets/vinyl-hero.LICENSE.md b/client/src/assets/vinyl-hero.LICENSE.md new file mode 100644 index 0000000..e591d27 --- /dev/null +++ b/client/src/assets/vinyl-hero.LICENSE.md @@ -0,0 +1,8 @@ +# Discover hero photograph + +- Photographer: Kevin McCutcheon +- Photo: [Black turntable on brown wooden table](https://unsplash.com/photos/black-turntable-on-brown-wooden-table-TcSckNRL9J8) +- License: [Unsplash License](https://unsplash.com/license), permitting downloading, modification, distribution and use, including commercial use. +- Source: https://images.unsplash.com/photo-1526394931762-90052e97b376 +- Local asset: vinyl-hero.webp (1800px wide WebP, quality 80). +- Used as a decorative CSS background with dark overlays. Attribution is also visible in the hero. diff --git a/client/src/assets/vinyl-hero.webp b/client/src/assets/vinyl-hero.webp new file mode 100644 index 0000000..c37d591 Binary files /dev/null and b/client/src/assets/vinyl-hero.webp differ diff --git a/client/src/components/AlbumCard.css b/client/src/components/AlbumCard.css index 60819f1..486e93b 100644 --- a/client/src/components/AlbumCard.css +++ b/client/src/components/AlbumCard.css @@ -1,38 +1,178 @@ .album-card { + position: relative; + isolation: isolate; + min-width: 0; height: 100%; - background: var(--surface); - border: 1px solid var(--border); - border-radius: 8px; + display: flex; + flex-direction: column; + overflow-wrap: anywhere; +} +.album-card__cover { + position: relative; + aspect-ratio: 1; overflow: hidden; + border: 1px solid var(--border); + border-radius: 3px; + background: var(--surface-raised); + display: grid; + place-items: center; +} +.album-card__record { + width: 68%; + aspect-ratio: 1; + border-radius: 50%; + border: 1px solid var(--border-strong); + background: repeating-radial-gradient( + circle, + var(--surface) 0 5px, + var(--border) 6px 7px + ); + display: grid; + place-items: center; + transition: transform 400ms ease; +} +.album-card__record::after { + content: ''; + width: 25%; + aspect-ratio: 1; + border-radius: 50%; + border: 1px solid var(--border-strong); + background: var(--surface-raised); +} +.album-card__view { + position: absolute; + right: 1rem; + bottom: 1rem; + color: var(--text); + background: var(--surface); + padding: 0.25rem 0.5rem; + border-radius: 3px; + font-size: 0.8rem; + transition: + opacity 180ms ease, + transform 180ms ease; +} +.album-card__view > span { + color: var(--accent); } .album-info { - height: 100%; + flex: 1; + min-width: 0; display: flex; flex-direction: column; - overflow-wrap: anywhere; - padding: 1rem; + padding: 1.125rem 1rem 1rem; +} +.album-card__topline { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: 0.5rem; + align-items: center; + color: var(--muted); + font-size: 0.8rem; +} +.album-card__rating { + display: inline-flex; + align-items: center; + gap: 0.35rem; +} +.album-card__rating svg { + flex-shrink: 0; +} +.album-card__rating--rated { + color: var(--accent); + font-weight: 700; +} +.album-card__rating--rated svg { + fill: currentColor; } .album-info h3 { - margin: 0; - font-size: 1.1rem; - line-height: 1.4; - overflow-wrap: anywhere; + margin: 0.5rem 0 0.25rem; + font-size: clamp(1.125rem, 1.65vw, 1.4375rem); + line-height: 1.25; + letter-spacing: -0.03em; } -.album-info h3 a { +.album-card__link { text-decoration: none; } -.album-info h3 a:hover { - text-decoration: underline; +/* Stretch the real album link across the card, below the separate crate control. */ +.album-card__link::after { + content: ''; + position: absolute; + inset: 0; + z-index: 1; + border-radius: 3px; } -.artist { - margin: 0.25rem 0; - color: var(--muted); - font-size: 0.9rem; +.album-card__link:focus-visible { + outline: none; +} +.album-card__link:focus-visible::after { + outline: 3px solid var(--focus); + outline-offset: 4px; } -.release-year { +.album-card .artist, +.album-card__reviews, +.album-card__genres-empty { color: var(--muted); - font-size: 0.9rem; - margin: 0.5rem 0; + margin: 0; + font-size: 0.875rem; +} +.album-card__reviews { + margin-top: 0.5rem; +} +.album-card__footer { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: end; + gap: 0.75rem; + margin-top: auto; + padding-top: 1rem; +} +.album-card .crate-button-wrap { + position: relative; + z-index: 2; + margin: 0; + max-width: 10rem; + justify-items: end; +} +.album-card .genre-tags { + margin: 0; +} +.album-card .genre-tags li { + border: 1px solid var(--border-strong); + border-radius: 100px; + padding: 0.25rem 0.625rem; + font-size: 0.75rem; + background: transparent; +} +.album-card:focus-within .album-card__record { + transform: scale(1.025); +} +@media (hover: hover) and (pointer: fine) { + .album-card__view { + opacity: 0; + transform: translateY(0.375rem); + } + .album-card:hover .album-card__view, + .album-card:focus-within .album-card__view { + opacity: 1; + transform: none; + } + .album-card:hover .album-card__record { + transform: scale(1.025); + } + .album-card:hover .album-card__link { + color: var(--accent); + } +} +@media (prefers-reduced-motion: reduce) { + .album-card .album-card__record, + .album-card:hover .album-card__record, + .album-card:focus-within .album-card__record, + .album-card .album-card__view { + transition: none; + transform: none; + } } .genre-tags { list-style: none; @@ -49,20 +189,3 @@ padding: 0.15rem 0.4rem; font-size: 0.8rem; } -.album-rating { - margin-top: auto; - border-top: 1px solid var(--border); - padding-top: 0.7rem; - display: flex; - flex-wrap: wrap; - justify-content: space-between; - gap: 0.4rem 0.75rem; - font-size: 0.875rem; -} -.album-rating > span:first-child { - color: var(--accent); - font-weight: 700; -} -.album-rating > span:last-child { - color: var(--muted); -} diff --git a/client/src/components/AlbumCard.test.tsx b/client/src/components/AlbumCard.test.tsx index 17f80f9..b83fef2 100644 --- a/client/src/components/AlbumCard.test.tsx +++ b/client/src/components/AlbumCard.test.tsx @@ -1,7 +1,21 @@ import { MockedProvider } from '@apollo/client/testing/react'; -import { it, expect } from 'vitest'; -import { render, screen } from '@testing-library/react'; +import { it, expect, vi } from 'vitest'; +import { render, screen, waitFor } from '@testing-library/react'; import AlbumCard from './AlbumCard.js'; +import userEvent from '@testing-library/user-event'; +import { ADD_TO_CRATE, REMOVE_FROM_CRATE } from '../api/crate.js'; +import type { AlbumSummary } from '../api/searchAlbums.js'; + +const album: AlbumSummary = { + id: '1', + title: 'A very long album title that should wrap naturally', + artists: [], + genres: [], + releaseYear: null, + averageRating: null, + reviewCount: 0, + isInCrate: false, +}; it('handles nullable summary fields without inventing a rating or year', () => { window.history.replaceState({}, '', '/?q=Abbey&sort=TITLE_ASC'); @@ -29,3 +43,109 @@ it('handles nullable summary fields without inventing a rating or year', () => { `${import.meta.env.BASE_URL}album/1?q=Abbey&sort=TITLE_ASC`, ); }); + +it('uses honest fallbacks and an unfilled rating indicator for missing metadata', () => { + render( + + + , + ); + expect(screen.getByRole('article', { name: 'Untitled album' })).toBeInTheDocument(); + expect(screen.getByText('Artist unknown')).toBeInTheDocument(); + expect(screen.getByText('Genre unknown')).toBeInTheDocument(); + const rating = screen.getByText('Not yet rated'); + expect(rating).not.toHaveClass('album-card__rating--rated'); + expect(rating.querySelector('svg')).toHaveAttribute('fill', 'none'); +}); + +it('shows a real aggregate rating and review count', () => { + render( + + + , + ); + expect(screen.getByText('4.3')).toBeInTheDocument(); + expect(screen.getByText('1 review')).toBeInTheDocument(); + expect(screen.getByText('Average rating:')).toBeInTheDocument(); +}); + +it.each([false, true])( + 'keeps keyboard navigation and the crate mutation separate (saved: %s)', + async (saved) => { + const result = vi.fn(() => ({ + data: saved + ? { + removeFromCrate: { + removedAlbumId: '1', + album: { __typename: 'Album', id: '1', isInCrate: false }, + }, + } + : { + addToCrate: { + item: { __typename: 'CrateItem', id: '1' }, + album: { __typename: 'Album', id: '1', isInCrate: true }, + }, + }, + })); + render( + + + , + ); + const link = screen.getByRole('link', { name: album.title }); + const open = vi.fn((event: Event) => event.preventDefault()); + link.addEventListener('click', open); + const button = screen.getByRole('button', { + name: saved ? 'In your crate, remove from crate' : 'Add to crate', + }); + expect(button.closest('a')).toBeNull(); + const user = userEvent.setup(); + await user.tab(); + expect(link).toHaveFocus(); + await user.keyboard('{Enter}'); + expect(open).toHaveBeenCalledTimes(1); + expect(result).not.toHaveBeenCalled(); + await user.tab(); + expect(button).toHaveFocus(); + await user.keyboard(' '); + await waitFor(() => { + expect(result).toHaveBeenCalledTimes(1); + expect(button).toHaveAttribute('aria-busy', 'false'); + }); + expect(open).toHaveBeenCalledTimes(1); + }, +); + +it('reports crate mutation errors without navigating', async () => { + const log = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + render( + + + , + ); + await userEvent.setup().click(screen.getByRole('button', { name: 'Add to crate' })); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Could not update your crate', + ); + } finally { + log.mockRestore(); + } +}); diff --git a/client/src/components/AlbumCard.tsx b/client/src/components/AlbumCard.tsx index 6e3f583..d752e08 100644 --- a/client/src/components/AlbumCard.tsx +++ b/client/src/components/AlbumCard.tsx @@ -5,35 +5,68 @@ import CrateButton from './CrateButton.js'; export default function AlbumCard({ album }: { album: AlbumSummary }) { const detailHref = `${import.meta.env.BASE_URL}album/${album.id}${window.location.search}`; + const rating = album.reviewCount > 0 ? album.averageRating : null; return (
+
-

- {album.title} -

-

{album.artists.map((artist) => artist.name).join(', ')}

-

{album.releaseYear ?? 'Year unknown'}

- -
    - {album.genres.map((genre) => ( -
  • {genre.name}
  • - ))} -
-
- - - {album.averageRating === null ? ( - 'Not yet rated' - ) : ( - <> +
+ {album.releaseYear ?? 'Year unknown'} + + + {rating !== null ? ( + Average rating: - {album.averageRating.toFixed(1)} + {rating.toFixed(1)} out of 5 - + + ) : ( + 'Not yet rated' )} - {album.reviewCount.toLocaleString('en-US')} reviews +
+

+ + {album.title || 'Untitled album'} + +

+

+ {album.artists.map((artist) => artist.name).join(', ') || 'Artist unknown'} +

+

+ {album.reviewCount.toLocaleString('en-US')}{' '} + {album.reviewCount === 1 ? 'review' : 'reviews'} +

+
+ {album.genres.length > 0 ? ( +
    + {album.genres.map((genre) => ( +
  • {genre.name}
  • + ))} +
+ ) : ( +

Genre unknown

+ )} +
diff --git a/client/src/components/BackToTop.css b/client/src/components/BackToTop.css new file mode 100644 index 0000000..015f556 --- /dev/null +++ b/client/src/components/BackToTop.css @@ -0,0 +1,38 @@ +.back-to-top { + position: fixed; + right: max(0.75rem, env(safe-area-inset-right)); + top: max(1rem, env(safe-area-inset-top)); + z-index: 2; + display: flex; + align-items: center; + justify-content: center; + gap: 0.375rem; + width: fit-content; + max-width: calc(100% - 1.5rem); + min-height: 2.75rem; + padding: 0.5rem; + border: 1px solid var(--accent); + border-radius: 100px; + background: var(--surface); + color: var(--accent); + box-shadow: 0 2px 8px rgb(0 0 0 / 20%); + font-size: 0.875rem; + font-weight: 700; +} + +.back-to-top span { + font-size: 1.25rem; +} + +.back-to-top:hover { + background: var(--surface-raised); + border-color: var(--accent-hover); +} + +@media (max-width: 700px) { + .back-to-top { + /* Keep narrow-screen controls clear, including with enlarged text. */ + position: static; + margin: 1.5rem 0 0 auto; + } +} diff --git a/client/src/components/BackToTop.test.tsx b/client/src/components/BackToTop.test.tsx new file mode 100644 index 0000000..f639c8a --- /dev/null +++ b/client/src/components/BackToTop.test.tsx @@ -0,0 +1,62 @@ +import { afterEach, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import BackToTop from './BackToTop.js'; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +it('appears after 600px, hides near the top and removes its listener on unmount', () => { + vi.stubGlobal('scrollY', 0); + const removeListener = vi.spyOn(window, 'removeEventListener'); + const { unmount } = render(); + expect(screen.queryByRole('button', { name: 'Back to top' })).not.toBeInTheDocument(); + vi.stubGlobal('scrollY', 601); + fireEvent.scroll(window); + expect(screen.getByRole('button', { name: 'Back to top' })).toHaveTextContent('Top'); + vi.stubGlobal('scrollY', 600); + fireEvent.scroll(window); + expect(screen.queryByRole('button', { name: 'Back to top' })).not.toBeInTheDocument(); + unmount(); + expect(removeListener).toHaveBeenCalledWith('scroll', expect.any(Function)); +}); + +it.each([ + ['click', false, 'smooth'], + ['{Enter}', false, 'smooth'], + [' ', true, 'instant'], +] as const)( + 'returns to the top with %j, respecting motion preferences and restoring focus', + async (activation, reducedMotion, behavior) => { + vi.stubGlobal('scrollY', 601); + const scrollTo = vi.fn(); + vi.stubGlobal('scrollTo', scrollTo); + vi.stubGlobal( + 'matchMedia', + vi.fn(() => ({ matches: reducedMotion })), + ); + render( +
+ +
, + ); + const button = screen.getByRole('button', { name: 'Back to top' }); + const user = userEvent.setup(); + if (activation === 'click') { + await user.click(button); + } else { + await user.tab(); + expect(button).toHaveFocus(); + await user.keyboard(activation); + } + expect(scrollTo).toHaveBeenCalledWith({ top: 0, behavior }); + expect(window.matchMedia).toHaveBeenCalledWith('(prefers-reduced-motion: reduce)'); + vi.stubGlobal('scrollY', 0); + fireEvent.scroll(window); + expect(screen.queryByRole('button', { name: 'Back to top' })).not.toBeInTheDocument(); + expect(screen.getByRole('main')).toHaveFocus(); + }, +); diff --git a/client/src/components/BackToTop.tsx b/client/src/components/BackToTop.tsx new file mode 100644 index 0000000..c379e3c --- /dev/null +++ b/client/src/components/BackToTop.tsx @@ -0,0 +1,37 @@ +import { useEffect, useState } from 'react'; + +import './BackToTop.css'; + +export default function BackToTop() { + const [visible, setVisible] = useState(false); + + useEffect(() => { + const updateVisibility = () => setVisible(window.scrollY > 600); + updateVisibility(); + window.addEventListener('scroll', updateVisibility, { passive: true }); + return () => window.removeEventListener('scroll', updateVisibility); + }, []); + + if (!visible) return null; + + return ( + + ); +} diff --git a/client/src/components/CrateButton.css b/client/src/components/CrateButton.css index 40072b5..42f2cb1 100644 --- a/client/src/components/CrateButton.css +++ b/client/src/components/CrateButton.css @@ -13,13 +13,26 @@ border: 1px solid var(--accent); color: var(--accent); } -.crate-button:not(.crate-button--saved):not(:disabled):hover { +.crate-button:not(.crate-button--saved):not([aria-disabled='true']):hover { background: var(--chip-bg); } .crate-button.crate-button--saved { background: var(--accent); color: var(--accent-text); } -.crate-button--saved:not(:disabled):hover { +.crate-button--saved:not([aria-disabled='true']):hover { background: var(--accent-hover); } + +.crate-button--compact { + display: grid; + place-items: center; + min-width: 2.75rem; + min-height: 2.75rem; + padding: 0.5rem; + border-radius: 50%; +} + +.crate-button[aria-disabled='true'] { + cursor: wait; +} diff --git a/client/src/components/CrateButton.test.tsx b/client/src/components/CrateButton.test.tsx index 6591e35..0bd57ea 100644 --- a/client/src/components/CrateButton.test.tsx +++ b/client/src/components/CrateButton.test.tsx @@ -1,11 +1,13 @@ import { gql } from '@apollo/client'; import { MockedProvider } from '@apollo/client/testing/react'; import { useQuery } from '@apollo/client/react'; -import { fireEvent, render, screen } from '@testing-library/react'; -import { expect, it } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { expect, it, vi } from 'vitest'; +import axe from 'axe-core'; import { ADD_TO_CRATE, REMOVE_FROM_CRATE } from '../api/crate.js'; import CrateButton from './CrateButton.js'; +import userEvent from '@testing-library/user-event'; const GET_ALBUM_CRATE_STATE = gql` query AlbumCrateState($id: ID!) { @@ -25,7 +27,7 @@ function CrateViews() { return ( <>
- +
@@ -35,7 +37,7 @@ function CrateViews() { } it('keeps list and detail crate controls in sync after add and remove', async () => { - render( + const { container } = render( , ); - const buttons = await screen.findAllByRole('button', { name: 'Add to crate' }); + const buttons = await screen.findAllByRole('button', { + name: 'Add to crate', + pressed: false, + }); + expect(buttons[1]).toHaveTextContent('Add to crate'); + expect( + ( + await axe.run(container, { + runOnly: ['label-content-name-mismatch', 'button-name'], + }) + ).violations, + ).toEqual([]); fireEvent.click(buttons[0]!); const addedButtons = await screen.findAllByRole('button', { - name: 'Remove from crate', + name: 'In your crate, remove from crate', + pressed: true, }); expect(addedButtons).toHaveLength(2); + expect(addedButtons[1]).toHaveTextContent('In your crate'); expect(addedButtons[0]).toHaveAttribute('aria-pressed', 'true'); expect(addedButtons[1]).toHaveAttribute('aria-pressed', 'true'); + expect( + ( + await axe.run(container, { + runOnly: ['label-content-name-mismatch', 'button-name'], + }) + ).violations, + ).toEqual([]); fireEvent.click(addedButtons[1]!); - const removedButtons = await screen.findAllByRole('button', { name: 'Add to crate' }); + const removedButtons = await screen.findAllByRole('button', { + name: 'Add to crate', + pressed: false, + }); expect(removedButtons).toHaveLength(2); + expect(removedButtons[1]).toHaveTextContent('Add to crate'); expect(removedButtons[0]).toHaveAttribute('aria-pressed', 'false'); expect(removedButtons[1]).toHaveAttribute('aria-pressed', 'false'); }); + +it('retains focus through repeated toggles and ignores activation while a mutation is pending', async () => { + const addResult = vi.fn(() => ({ + data: { + addToCrate: { + item: { __typename: 'CrateItem', id: '1' }, + album: { __typename: 'Album', id: '1', isInCrate: true }, + }, + }, + })); + const removeResult = vi.fn(() => ({ + data: { + removeFromCrate: { + removedAlbumId: '1', + album: { __typename: 'Album', id: '1', isInCrate: false }, + }, + }, + })); + render( + + + , + ); + const [button, regularButton] = await screen.findAllByRole('button', { + name: 'Add to crate', + }); + const user = userEvent.setup(); + await user.tab(); + expect(button).toHaveFocus(); + // Two synchronous clicks must still start only one mutation. + fireEvent.click(button!); + fireEvent.click(button!); + expect(button).toHaveAttribute('aria-disabled', 'true'); + expect(button).not.toBeDisabled(); + expect(button).toHaveFocus(); + await user.keyboard('{Enter} '); + await waitFor(() => expect(button).toHaveAttribute('aria-pressed', 'true')); + expect(addResult).toHaveBeenCalledTimes(1); + expect(button).toHaveFocus(); + expect(button).toHaveAccessibleName('In your crate, remove from crate'); + await user.keyboard('{Enter}'); + await waitFor(() => expect(button).toHaveAttribute('aria-pressed', 'false')); + expect(removeResult).toHaveBeenCalledTimes(1); + expect(button).toHaveAccessibleName('Add to crate'); + expect(button).toHaveFocus(); + await user.keyboard(' '); + await waitFor(() => expect(button).toHaveAttribute('aria-pressed', 'true')); + expect(addResult).toHaveBeenCalledTimes(2); + expect(button).toHaveFocus(); + await user.tab(); + expect(regularButton).toHaveFocus(); + await user.tab({ shift: true }); + expect(button).toHaveFocus(); +}); diff --git a/client/src/components/CrateButton.tsx b/client/src/components/CrateButton.tsx index f7dab73..df8bbb6 100644 --- a/client/src/components/CrateButton.tsx +++ b/client/src/components/CrateButton.tsx @@ -1,13 +1,14 @@ import './CrateButton.css'; -import { useState } from 'react'; +import { useRef, useState } from 'react'; import { useMutation } from '@apollo/client/react'; import { ADD_TO_CRATE, REMOVE_FROM_CRATE } from '../api/crate.js'; -type Props = { albumId: string; isInCrate: boolean }; +type Props = { albumId: string; isInCrate: boolean; compact?: boolean }; -export default function CrateButton({ albumId, isInCrate }: Props) { +export default function CrateButton({ albumId, isInCrate, compact = false }: Props) { + const mutationInFlight = useRef(false); const [error, setError] = useState(null); const [addToCrate, addState] = useMutation(ADD_TO_CRATE, { update(cache, { data }) { @@ -28,6 +29,9 @@ export default function CrateButton({ albumId, isInCrate }: Props) { const busy = addState.loading || removeState.loading; async function toggle() { + // aria-disabled keeps keyboard focus; this guard also blocks clicks before React rerenders. + if (busy || mutationInFlight.current) return; + mutationInFlight.current = true; setError(null); try { if (isInCrate) { @@ -38,21 +42,41 @@ export default function CrateButton({ albumId, isInCrate }: Props) { } catch (caught) { console.error('Could not update crate:', caught); setError('Could not update your crate. Please try again.'); + } finally { + mutationInFlight.current = false; } } return ( {error && ( diff --git a/client/src/components/FilterPanel.css b/client/src/components/FilterPanel.css index 4a016d4..8a9affc 100644 --- a/client/src/components/FilterPanel.css +++ b/client/src/components/FilterPanel.css @@ -1,63 +1,150 @@ .filter-panel { - margin-bottom: 1.25rem; + border-block: 1px solid var(--border); + margin: 1rem 0 1.75rem; } -.filter-panel fieldset { +.filter-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.75rem 1rem; + padding-block: 0.875rem; +} +.filter-toggle, +.clear-filters { + min-height: 2.75rem; + background: var(--surface); + color: var(--text); + border: 1px solid var(--border-strong); + padding: 0.5rem 0.875rem; + font-size: 0.875rem; +} +.filter-toggle { + border-radius: 100px; +} +.filter-toggle[aria-expanded='true'] { + border-color: var(--accent); + color: var(--accent); + background: var(--chip-bg); +} +.filter-options { + border-top: 1px solid var(--border); + padding: 0.875rem 0; +} +.filter-panel-header { + display: flex; + flex-wrap: wrap; + align-items: start; + justify-content: space-between; + gap: 0.75rem; + margin-bottom: 0.75rem; +} +.filter-panel-header h3 { + margin: 0; + font-size: 1rem; +} +.filter-panel-message { + color: var(--muted); + margin: 0.25rem 0 0; + font-size: 0.875rem; +} +.filter-groups { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 24rem), 1fr)); + align-items: start; + gap: 1rem 1.5rem; +} +.filter-column { + display: grid; + align-content: start; + min-width: 0; + gap: 1rem; +} +.filter-groups fieldset { + min-width: 0; border: 0; margin: 0; - padding: 0.5rem 0; + padding: 0; +} +.filter-group--reviews { + width: fit-content; + max-width: 100%; } -.filter-panel legend { +.filter-groups legend { + color: var(--muted); padding: 0; + margin-bottom: 0.5rem; font-size: 0.75rem; font-weight: 700; - text-transform: uppercase; letter-spacing: 0.1em; - color: var(--muted); + text-transform: uppercase; } -.filter-panel label { +.filter-list { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 10rem), 1fr)); + gap: 0.375rem; +} +.filter-list label { display: flex; align-items: center; - gap: 0.5rem; - padding: 0.25rem 0; -} -.filter-count { - margin-left: auto; - font-size: 0.8rem; - color: var(--chip-text); - background: var(--chip-bg); - border-radius: 999px; - padding: 0 0.5rem; -} -.clear-filters { - background: var(--surface); - color: var(--text); + gap: 0.375rem; + min-height: 2rem; + min-width: 0; + max-width: 100%; border: 1px solid var(--border-strong); -} -.filter-toggle { + border-radius: 4px; + padding: 0.25rem 0.5rem; background: var(--surface); color: var(--text); - border: 1px solid var(--border-strong); + font-size: 0.8125rem; + cursor: pointer; + overflow-wrap: anywhere; } -.filter-toggle[aria-expanded='true'] { - border-color: var(--accent); +.filter-list input { + flex-shrink: 0; + accent-color: var(--accent); } -.filter-options:not(.open) { - display: none; +.filter-count { + flex-shrink: 0; + color: var(--muted); + font-size: 0.75rem; + margin-left: auto; } -.filter-options.open { +.active-filters { display: flex; flex-wrap: wrap; - align-items: flex-start; - gap: 0 2rem; - margin-top: 0.75rem; - padding: 0.75rem 1rem; - border: 1px solid var(--border); - border-radius: 8px; - background: var(--surface); + gap: 0.5rem; + list-style: none; + margin: 0; + padding: 0 0 0.875rem; +} +.active-filters li { + max-width: 100%; +} +.active-filters button { + max-width: 100%; + min-height: 2rem; + padding: 0.25rem 0.625rem; + border: 1px solid var(--border-strong); + border-radius: 100px; + background: var(--chip-bg); + color: var(--chip-text); + font-size: 0.8rem; + overflow-wrap: anywhere; } -.filter-options fieldset { - min-width: 11rem; +.clear-filters, +.show-genres { + min-height: 2rem; + padding: 0.25rem 0.625rem; + font-size: 0.8125rem; } -.filter-options .clear-filters { - align-self: center; +.show-genres { + margin-top: 0.5rem; + border: 1px solid var(--border-strong); + background: var(--surface); + color: var(--accent); +} + +.clear-filters[aria-disabled='true'] { + color: var(--muted); + cursor: default; } diff --git a/client/src/components/FilterPanel.test.tsx b/client/src/components/FilterPanel.test.tsx index f282dac..7b7304c 100644 --- a/client/src/components/FilterPanel.test.tsx +++ b/client/src/components/FilterPanel.test.tsx @@ -1,11 +1,12 @@ import { describe, expect, it, vi } from 'vitest'; -import { fireEvent, render, screen } from '@testing-library/react'; +import { fireEvent, render, screen, within } from '@testing-library/react'; import axe from 'axe-core'; import FilterPanel from './FilterPanel.js'; +import userEvent from '@testing-library/user-event'; type Props = Parameters[0]; -function renderPanel(over: Partial = {}) { +function renderPanel(over: Partial = {}, expanded = true) { const props: Props = { genres: [], decades: [], @@ -25,7 +26,9 @@ function renderPanel(over: Partial = {}) { onClear: vi.fn(), ...over, }; - return { props, ...render() }; + const view = render(); + if (expanded) fireEvent.click(screen.getByRole('button', { name: /^Filters/ })); + return { props, ...view }; } describe('FilterPanel', () => { @@ -45,43 +48,40 @@ describe('FilterPanel', () => { 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', () => { + it('keeps Clear filters inactive when nothing is selected', () => { renderPanel(); - expect(screen.queryByRole('button', { name: 'Clear filters' })).toBeNull(); + expect(screen.getByRole('button', { name: 'Clear filters' })).toHaveAttribute( + 'aria-disabled', + 'true', + ); }); - it('clears every filter', () => { + it('clears every filter with Space', async () => { const { props } = renderPanel({ reviewed: true }); - fireEvent.click(screen.getByRole('button', { name: 'Clear filters' })); - expect(props.onClear).toHaveBeenCalled(); + screen.getByRole('button', { name: 'Clear filters' }).focus(); + await userEvent.setup().keyboard(' '); + expect(props.onClear).toHaveBeenCalledTimes(1); }); - 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)' }); + it('toggles the options with Space and Enter while showing active filters', async () => { + renderPanel({ genres: ['4'], decades: [1970], reviewed: true }, false); + const button = screen.getByRole('button', { name: 'Filters (3)' }); + expect(screen.queryByRole('checkbox')).not.toBeInTheDocument(); + expect(screen.getByRole('list', { name: 'Active filters' })).toHaveTextContent( + /Rock.*1970s.*Has reviews/, + ); expect(button).toHaveAttribute('aria-expanded', 'false'); expect(button).toHaveAttribute('aria-controls', 'filter-options'); - fireEvent.click(button); + const user = userEvent.setup(); + button.focus(); + await user.keyboard(' '); expect(button).toHaveAttribute('aria-expanded', 'true'); + await user.keyboard('{Enter}'); + expect(button).toHaveAttribute('aria-expanded', 'false'); }); it('closes on Escape and returns focus to the Filters button', () => { - renderPanel(); + renderPanel({}, false); const button = screen.getByRole('button', { name: 'Filters' }); fireEvent.click(button); fireEvent.keyDown(screen.getByRole('checkbox', { name: /Rock/ }), { key: 'Escape' }); @@ -89,12 +89,189 @@ describe('FilterPanel', () => { 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('makes every active filter available as a removable chip', () => { + renderPanel({ + decades: [1950, 1960, 1970, 1980, 1990], + decadeFacets: [1950, 1960, 1970, 1980, 1990].map((decade) => ({ + decade, + count: 1, + })), + }); + expect( + within(screen.getByRole('list', { name: 'Active filters' })).getAllByRole('button'), + ).toHaveLength(5); + expect(screen.getAllByRole('checkbox', { checked: true })).toHaveLength(5); + }); + + it('shows more/fewer genres and always retains selected genres outside the preview', async () => { + const { props } = renderPanel({ + genres: ['9'], + genreFacets: Array.from({ length: 10 }, (_, i) => ({ + genre: { id: String(i + 1), name: 'Genre ' + (i + 1) }, + count: i === 8 ? 0 : i + 1, + })), + }); + const group = screen.getByRole('group', { name: 'Genre' }); + expect(within(group).getAllByRole('checkbox')).toHaveLength(7); + expect(screen.getByRole('checkbox', { name: 'Genre 9 0 albums' })).toBeChecked(); + expect( + screen.queryByRole('checkbox', { name: 'Genre 10 10 albums' }), + ).not.toBeInTheDocument(); + const more = screen.getByRole('button', { name: 'Show more genres' }); + const user = userEvent.setup(); + more.focus(); + await user.keyboard(' '); + expect(more).toHaveAttribute('aria-expanded', 'true'); + expect(within(group).getAllByRole('checkbox')).toHaveLength(10); + // Newly revealed options precede the disclosure button in keyboard order. + await user.tab({ shift: true }); + expect(screen.getByRole('checkbox', { name: 'Genre 10 10 albums' })).toHaveFocus(); + await user.keyboard(' '); + expect(props.onGenresChange).toHaveBeenCalledWith(['9', '10']); + await user.tab(); + await user.keyboard('{Enter}'); + expect(more).toHaveAccessibleName('Show more genres'); + expect(more).toHaveFocus(); + expect(more).toHaveAttribute('aria-expanded', 'false'); + expect( + screen.queryByRole('checkbox', { name: 'Genre 10 10 albums' }), + ).not.toBeInTheDocument(); + expect(screen.getByRole('checkbox', { name: 'Genre 9 0 albums' })).toBeChecked(); + }); + + it('removes each filter independently and returns focus to the Filters toggle', async () => { + const { props } = renderPanel( + { genres: ['4', '2'], decades: [1970], reviewed: true }, + false, + ); + const user = userEvent.setup(); + screen.getByRole('button', { name: 'Remove genre filter: Rock' }).focus(); + await user.keyboard(' '); + expect(props.onGenresChange).toHaveBeenCalledWith(['2']); + expect(props.onDecadesChange).not.toHaveBeenCalled(); + expect(props.onReviewedChange).not.toHaveBeenCalled(); + expect(screen.getByRole('button', { name: 'Filters (4)' })).toHaveFocus(); + screen.getByRole('button', { name: 'Remove decade filter: 1970s' }).focus(); + await user.keyboard('{Enter}'); + expect(props.onDecadesChange).toHaveBeenCalledWith([]); + screen.getByRole('button', { name: 'Remove review filter: Has reviews' }).focus(); + await user.keyboard(' '); + expect(props.onReviewedChange).toHaveBeenCalledWith(false); + expect(props.onClear).not.toHaveBeenCalled(); + }); + + it('shows decades newest first without mutating incoming facets', () => { + const facets = [ + { decade: 1980, count: 3 }, + { decade: 2020, count: 2 }, + { decade: 1960, count: 1 }, + ]; + renderPanel({ decadeFacets: facets }); + expect( + within(screen.getByRole('group', { name: 'Decade' })) + .getAllByRole('checkbox') + .map((input) => input.closest('label')?.textContent), + ).toEqual(['2020s 2 albums', '1980s 3 albums', '1960s 1 albums']); + expect(facets.map(({ decade }) => decade)).toEqual([1980, 2020, 1960]); + }); + + it.each([ + ['Rock 7 albums', 'genres', ['4'], 'onGenresChange', []], + ['1970s 3 albums', 'decades', [1970], 'onDecadesChange', []], + ['Has reviews 2 albums', 'reviewed', true, 'onReviewedChange', false], + ] as const)( + 'uses Space, not Enter, to toggle %s', + async (name, field, selected, callback, cleared) => { + const { props, rerender } = renderPanel(); + const input = screen.getByRole('checkbox', { name }); + const user = userEvent.setup(); + input.focus(); + await user.keyboard('{Enter}'); + expect(props[callback]).not.toHaveBeenCalled(); + expect(input).not.toBeChecked(); + await user.keyboard(' '); + expect(props[callback]).toHaveBeenLastCalledWith(selected); + rerender(); + expect(input).toBeChecked(); + expect(input).toHaveFocus(); + await user.keyboard(' '); + expect(props[callback]).toHaveBeenLastCalledWith(cleared); + }, + ); + + it('tabs through visible categories in reading order', async () => { + renderPanel({}, false); + const user = userEvent.setup(); + await user.tab(); + expect(screen.getByRole('button', { name: 'Filters' })).toHaveFocus(); + await user.keyboard('{Enter}'); + await user.tab(); + expect(screen.getByRole('button', { name: 'Clear filters' })).toHaveFocus(); + for (const name of ['Rock 7 albums', 'Has reviews 2 albums', '1970s 3 albums']) { + await user.tab(); + expect(screen.getByRole('checkbox', { name })).toHaveFocus(); + } }); + it.each(['preview', 'zero count'])( + 'keeps keyboard focus when removing a %s genre hides its checkbox', + async (reason) => { + const selectedId = reason === 'zero count' ? '0' : '6'; + const facets = Array.from({ length: 7 }, (_, i) => ({ + genre: { id: String(i), name: 'Genre ' + i }, + count: reason === 'zero count' && i === 0 ? 0 : 1, + })); + const { props, rerender } = renderPanel({ + genres: [selectedId], + genreFacets: facets, + }); + const name = new RegExp('^Genre ' + selectedId + ' '); + const input = screen.getByRole('checkbox', { name }); + expect(input).toBeChecked(); + input.focus(); + await userEvent.setup().keyboard(' '); + rerender(); + expect(screen.queryByRole('checkbox', { name })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Filters' })).toHaveFocus(); + }, + ); + + it.each<[string, Partial]>([ + [ + 'Genre 6 0 albums', + { genres: ['6'], genreFacets: [{ genre: { id: '6', name: 'Genre 6' }, count: 0 }] }, + ], + ['1970s 0 albums', { decades: [1970], decadeFacets: [{ decade: 1970, count: 0 }] }], + ['Has reviews 0 albums', { reviewed: true, reviewedCount: 0 }], + ])('does not steal focus when %s changes without being focused', (name, filters) => { + renderPanel(filters); + const clear = screen.getByRole('button', { name: 'Clear filters' }); + clear.focus(); + fireEvent.click(screen.getByRole('checkbox', { name })); + expect(clear).toHaveFocus(); + }); + + it.each<[string, Partial, Partial]>([ + [ + '1970s 0 albums', + { decades: [1970], decadeFacets: [{ decade: 1970, count: 0 }] }, + { decades: [] }, + ], + ['Has reviews 0 albums', { reviewed: true, reviewedCount: 0 }, { reviewed: false }], + ])( + 'returns focus only when the focused zero-count option %s disappears', + async (name, filters, cleared) => { + const { props, rerender } = renderPanel(filters); + const input = screen.getByRole('checkbox', { name }); + expect(input).toBeChecked(); + input.focus(); + await userEvent.setup().keyboard(' '); + rerender(); + expect(screen.queryByRole('checkbox', { name })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: /^Filters/ })).toHaveFocus(); + }, + ); + 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 afa0704..ac96be9 100644 --- a/client/src/components/FilterPanel.tsx +++ b/client/src/components/FilterPanel.tsx @@ -1,10 +1,11 @@ import './FilterPanel.css'; -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState, type ReactNode } from 'react'; import type { DecadeFacet, GenreFacet } from '../api/searchAlbums.js'; interface Props { + children?: ReactNode; genres: string[]; decades: number[]; reviewed: boolean; @@ -17,6 +18,8 @@ interface Props { onClear: () => void; } +const GENRE_PREVIEW_COUNT = 6; + function toggle(list: T[], value: T): T[] { return list.includes(value) ? list.filter((item) => item !== value) : [...list, value]; } @@ -30,20 +33,57 @@ function toggle(list: T[], value: T): T[] { * * 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. + * button. Toolbar children provide the result summary and sorting control. */ 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), - ); + // Presentation order of facet options only; album sorting stays on the server. + const decades = props.decadeFacets + .filter(({ decade, count }) => count > 0 || props.decades.includes(decade)) + .sort((a, b) => b.decade - a.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 activeFilters = [ + ...props.genres.map((id) => { + const name = + props.genreFacets.find(({ genre }) => genre.id === id)?.genre.name ?? id; + return { + key: 'genre-' + id, + label: name, + removeLabel: 'Remove genre filter: ' + name, + remove: () => + props.onGenresChange(props.genres.filter((genreId) => genreId !== id)), + }; + }), + ...props.decades.map((decade) => ({ + key: 'decade-' + decade, + label: decade + 's', + removeLabel: 'Remove decade filter: ' + decade + 's', + remove: () => + props.onDecadesChange(props.decades.filter((value) => value !== decade)), + })), + ...(props.reviewed + ? [ + { + key: 'reviewed', + label: 'Has reviews', + removeLabel: 'Remove review filter: Has reviews', + remove: () => props.onReviewedChange(false), + }, + ] + : []), + ]; const [open, setOpen] = useState(false); + const [showAllGenres, setShowAllGenres] = useState(false); + // Selected genres stay visible even when they fall outside the preview. + const visibleGenres = genres.filter( + ({ genre }, index) => + showAllGenres || index < GENRE_PREVIEW_COUNT || props.genres.includes(genre.id), + ); const toggleRef = useRef(null); useEffect(() => { @@ -58,83 +98,164 @@ export default function FilterPanel(props: Props) { }, [open]); return ( - +
); } diff --git a/client/src/components/ResultsLayout.css b/client/src/components/ResultsLayout.css index 2ebbdfd..da45209 100644 --- a/client/src/components/ResultsLayout.css +++ b/client/src/components/ResultsLayout.css @@ -2,11 +2,14 @@ padding-bottom: 2.5rem; } .results-header { - display: flex; - flex-wrap: wrap; - align-items: baseline; - justify-content: space-between; - gap: 0.5rem 1rem; + margin-bottom: 1rem; +} +.results-summary { + flex: 1 1 14rem; + margin: 0; + color: var(--muted); + font-size: 0.875rem; + overflow-wrap: anywhere; } .pagination { @@ -19,8 +22,8 @@ margin: 0; padding: 0; display: grid; - grid-template-columns: repeat(3, minmax(0, 1fr)); - gap: 1.2rem; + grid-template-columns: repeat(auto-fill, minmax(min(100%, 18rem), 1fr)); + gap: 2.75rem 1.375rem; } .album-grid > li { min-width: 0; @@ -38,13 +41,3 @@ min-height: 3rem; margin: 0 0 1rem; } -@media (max-width: 1000px) { - .album-grid { - grid-template-columns: repeat(2, minmax(0, 1fr)); - } -} -@media (max-width: 600px) { - .album-grid { - grid-template-columns: minmax(0, 1fr); - } -} diff --git a/client/src/components/ResultsLayout.tsx b/client/src/components/ResultsLayout.tsx index 9449c99..2d43ada 100644 --- a/client/src/components/ResultsLayout.tsx +++ b/client/src/components/ResultsLayout.tsx @@ -1,11 +1,14 @@ import './ResultsLayout.css'; -import { useEffect, useRef } from 'react'; +import { useEffect, useRef, type ComponentProps } from 'react'; +import FilterPanel from './FilterPanel.js'; import AlbumCard from './AlbumCard.js'; import SortSelect from './SortSelect.js'; +import BackToTop from './BackToTop.js'; import type { AlbumSort, AlbumSummary } from '../api/searchAlbums.js'; interface Props { + filters: ComponentProps; albums: AlbumSummary[]; totalCount: number; hasQuery: boolean; @@ -84,61 +87,70 @@ export default function ResultsLayout(props: Props) { aria-busy={props.loading || props.loadingMore} >
-

Search results

- {props.hasQuery && ( - - )} +

+ {props.hasQuery ? 'Search results' : 'Browse albums'} +

-

- {!props.hasQuery - ? 'Search for an album or artist to get started.' - : props.loading + +

+ {props.loading ? props.retrying - ? 'Retrying search…' - : 'Searching albums…' + ? props.hasQuery + ? 'Retrying search…' + : 'Retrying albums…' + : props.hasQuery + ? 'Searching albums…' + : 'Loading albums…' : props.error - ? 'Search failed.' + ? props.hasQuery + ? 'Search failed.' + : 'Could not load albums.' : props.loadingMore ? 'Loading more albums…' - : `Showing ${props.albums.length} of ${props.totalCount} albums.`} -

- {props.hasQuery && - (props.error || props.retrying ? ( -
-

- Could not load albums. Please try again. -

- {/* Keep the button mounted so retrying does not discard keyboard focus. */} - -
- ) : props.loading ? null : props.totalCount === 0 ? ( -
-

No albums found

-

Try another album or artist.

- -
- ) : ( -
    - {props.albums.map((album) => ( -
  • - -
  • - ))} -
- ))} - {props.hasQuery && !props.loading && !props.error && props.hasNextPage && ( + : `Showing ${props.albums.length.toLocaleString('en-US')} of ${props.totalCount.toLocaleString('en-US')} matching albums.`} +

+ + + {props.error || props.retrying ? ( +
+

+ Could not load albums. Please try again. +

+ {/* Keep the button mounted so retrying does not discard keyboard focus. */} + +
+ ) : props.loading ? null : props.totalCount === 0 ? ( +
+

No albums found

+

+ {props.hasQuery + ? 'Try another album or artist, or clear filters.' + : 'Try clearing your filters.'} +

+ +
+ ) : ( +
    + {props.albums.map((album) => ( +
  • + +
  • + ))} +
+ )} + {!props.loading && !props.error && props.hasNextPage && (
{props.pageError && (

Could not load more albums. Please try again.

@@ -156,6 +168,7 @@ export default function ResultsLayout(props: Props) {
)} + ); } diff --git a/client/src/components/ReviewForm.css b/client/src/components/ReviewForm.css index 0c58c76..6fa4480 100644 --- a/client/src/components/ReviewForm.css +++ b/client/src/components/ReviewForm.css @@ -31,7 +31,7 @@ } .review-form textarea { background: var(--surface); - border: 1px solid var(--border); + border: 1px solid var(--border-strong); border-radius: 6px; color: var(--text); display: block; diff --git a/client/src/components/SearchForm.css b/client/src/components/SearchForm.css index 3198978..967b3e8 100644 --- a/client/src/components/SearchForm.css +++ b/client/src/components/SearchForm.css @@ -1,24 +1,56 @@ .search-form { display: flex; - gap: 0.6rem; - max-width: 640px; - margin: auto; + align-items: center; + gap: 0.5rem; + max-width: 42.5rem; + min-width: 0; + padding: 0.5rem; + border: 1px solid var(--border-strong); + border-radius: 5px; + background: var(--surface); + box-shadow: 0 1.125rem 3.75rem rgb(0 0 0 / 32%); +} +/* Input focus belongs to the whole field; the button keeps its own focus ring. */ +.search-form:has(input:focus-visible) { + outline: 3px solid var(--focus); + outline-offset: 4px; +} +.search-form input:focus-visible { + outline: none; +} +.search-form__icon { + flex-shrink: 0; + margin-left: 0.75rem; + color: var(--accent); } .search-form input { + flex: 1; width: 100%; min-width: 0; - padding: 0.9rem 1rem; - border: 1px solid var(--border-strong); - border-radius: 6px; - background: var(--surface); + min-height: 3rem; + padding: 0.75rem 1rem; + border: 0; + border-radius: 3px; + background: transparent; color: var(--text); } .search-form input::placeholder { color: var(--muted); opacity: 1; } -@media (max-width: 420px) { +.search-form button { + flex-shrink: 0; + min-height: 3rem; + padding: 0.75rem 1.625rem; + border-radius: 3px; + font-weight: 700; +} +@media (max-width: 35rem) { + .search-form__icon { + display: none; + } .search-form { flex-direction: column; + align-items: stretch; } } diff --git a/client/src/components/SearchForm.tsx b/client/src/components/SearchForm.tsx index 4c23b71..d0e148e 100644 --- a/client/src/components/SearchForm.tsx +++ b/client/src/components/SearchForm.tsx @@ -37,6 +37,20 @@ export default function SearchForm({ query, onSearch }: Props) { onSearch(draft.trim()); }} > + diff --git a/client/src/components/SortSelect.css b/client/src/components/SortSelect.css index 0264698..9a2c018 100644 --- a/client/src/components/SortSelect.css +++ b/client/src/components/SortSelect.css @@ -2,12 +2,18 @@ display: flex; align-items: center; gap: 0.5rem; + flex-wrap: wrap; + min-width: 0; + max-width: 100%; font-size: 0.9rem; } .sort-select label { color: var(--muted); } .sort-select select { + min-width: 0; + max-width: 100%; + min-height: 2.75rem; padding: 0.45rem 0.6rem; border: 1px solid var(--border-strong); border-radius: 6px; diff --git a/client/src/global.css b/client/src/global.css index 9161a44..31930e3 100644 --- a/client/src/global.css +++ b/client/src/global.css @@ -1,57 +1,98 @@ +/* Locally hosted variable fonts; load only the subsets used by the text. */ +@font-face { + font-family: 'DM Sans'; + font-style: normal; + font-weight: 400 700; + font-display: swap; + src: url('./assets/fonts/dm-sans-latin-ext.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, + U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, + U+2113, U+2C60-2C7F, U+A720-A7FF; +} + +@font-face { + font-family: 'DM Sans'; + font-style: normal; + font-weight: 400 700; + font-display: swap; + src: url('./assets/fonts/dm-sans-latin.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, + U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} + +@font-face { + font-family: 'Manrope'; + font-style: normal; + font-weight: 400 800; + font-display: swap; + src: url('./assets/fonts/manrope-latin-ext.woff2') format('woff2'); + unicode-range: + U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, + U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, + U+2113, U+2C60-2C7F, U+A720-A7FF; +} + +@font-face { + font-family: 'Manrope'; + font-style: normal; + font-weight: 400 800; + font-display: swap; + src: url('./assets/fonts/manrope-latin.woff2') format('woff2'); + unicode-range: + U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, + U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; +} + :root { color-scheme: light; - --bg: #f7f5ef; - --surface: #fffefa; - --text: #202824; - --muted: #61665e; - --accent: #285943; - --accent-hover: #1c4230; + --bg: #f4f7f3; + --surface: #ffffff; + --surface-raised: #e8f0e9; + --text: #17251c; + --muted: #526257; + --accent: #246443; + --accent-hover: #194d32; --accent-text: #ffffff; - --border: #dedfd5; - --border-strong: #b7bfb3; - --chip-bg: #eff0e9; - --chip-text: #50574c; - --header-bg: #181e1b; - --header-text: #f7f5ef; - --header-accent: #a9c3a3; + --border: #d0dbd2; + /* Controls need more contrast than decorative dividers. */ + --border-strong: #7b8a80; + --chip-bg: var(--surface-raised); + --chip-text: #405b49; + --header-bg: #0a100d; + --header-text: #f2f5ee; + --header-accent: #8ce3b5; --focus: #2874c5; - font-family: - system-ui, - -apple-system, - 'Segoe UI', - sans-serif; + --danger: #a32626; + --font-body: 'DM Sans', system-ui, -apple-system, 'Segoe UI', sans-serif; + --font-display: 'Manrope', var(--font-body); + font-family: var(--font-body); line-height: 1.5; font-synthesis: none; } -/* - * Dark theme. One of the bærekraft measures: an OLED screen draws measurably - * less power on a dark pixel than a light one, so a dark theme is not only a - * preference, it is energy saved for anyone whose system asks for it. - * - * The light values above are untouched; these only override them when the OS - * reports a dark preference. Contrast is AA or better for every text pair and - * 3:1 or better for the form-control borders. - */ + +/* Follow the system preference; the light theme uses darker green accents + so text and controls retain their contrast on pale surfaces. */ @media (prefers-color-scheme: dark) { :root { color-scheme: dark; - --bg: #141814; - --surface: #1c211c; - --text: #ecefe9; - --muted: #a4ab9f; - --accent: #7fc9a0; - --accent-hover: #a5dcbb; - --accent-text: #12261c; - --border: #3a443a; - --border-strong: #6b766b; - --chip-bg: #262d26; - --chip-text: #c3cabc; - --header-bg: #0e120e; - --header-text: #ecefe9; - --header-accent: #7fc9a0; - --focus: #79b8f0; + --bg: #0a100d; + --surface: #111914; + --surface-raised: #17211b; + --text: #f2f5ee; + --muted: #a4aea3; + --accent: #8ce3b5; + --accent-hover: #adf4cc; + --accent-text: #0a100d; + --border: #28362e; + --border-strong: #687d6e; + --chip-text: #b9c8bc; + --focus: #8ce3b5; + --danger: #ffaaaa; } } + * { box-sizing: border-box; } @@ -63,9 +104,13 @@ body { a { color: inherit; } +:where(h1, h2, h3, h4, h5, h6) { + font-family: var(--font-display); +} button, input, -select { +select, +textarea { font: inherit; } button, diff --git a/client/src/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts index 95b2ae7..8070e4c 100644 --- a/client/src/hooks/useAlbumSearch.ts +++ b/client/src/hooks/useAlbumSearch.ts @@ -1,5 +1,5 @@ import { useCallback, useMemo, useRef, useState } from 'react'; -import { skipToken, useQuery } from '@apollo/client/react'; +import { useQuery } from '@apollo/client/react'; import { NetworkStatus } from '@apollo/client'; import { SEARCH_ALBUMS, type AlbumSearchInput } from '../api/searchAlbums.js'; @@ -9,8 +9,16 @@ const PAGE_SIZE = 20; const AUTOMATIC_PAGE_LIMIT = 2; export function useAlbumSearch() { - const { state, setQuery, setSort, setGenres, setDecades, setReviewed, clearFilters } = - useSearchState(); + const { + state, + setQuery, + setSort, + setGenres, + setDecades, + setReviewed, + clearFilters, + resetSearch, + } = useSearchState(); const query = state.q; const hasQuery = query.length > 0; const retryInFlight = useRef(false); @@ -30,15 +38,10 @@ export function useAlbumSearch() { ); const { data, previousData, loading, error, refetch, fetchMore, networkStatus } = - useQuery( - SEARCH_ALBUMS, - hasQuery - ? { - variables: { input, first: PAGE_SIZE, after: null }, - fetchPolicy: 'cache-first', - } - : skipToken, - ); + useQuery(SEARCH_ALBUMS, { + variables: { input, first: PAGE_SIZE, after: null }, + fetchPolicy: 'cache-first', + }); const key = JSON.stringify(input); const [pagination, setPagination] = useState({ @@ -69,7 +72,7 @@ export function useAlbumSearch() { const hasCachedPage = edges.length > pagination.visibleCount; const hasNextPage = - hasQuery && (hasCachedPage || Boolean(pageInfo?.hasNextPage && pageInfo.endCursor)); + hasCachedPage || Boolean(pageInfo?.hasNextPage && pageInfo.endCursor); const loadPage = useCallback( (automatic: boolean) => { @@ -148,7 +151,7 @@ export function useAlbumSearch() { const loadMoreAutomatically = useCallback(() => loadPage(true), [loadPage]); const retry = useCallback(() => { - if (!hasQuery || !error || loading || retryInFlight.current) { + if (!error || loading || retryInFlight.current) { return; } @@ -161,7 +164,7 @@ export function useAlbumSearch() { .finally(() => { retryInFlight.current = false; }); - }, [hasQuery, error, loading, refetch]); + }, [error, loading, refetch]); const search = useCallback( (text: string) => { @@ -188,23 +191,22 @@ export function useAlbumSearch() { reviewed: state.reviewed, }, facets: { - genres: hasQuery ? (facets?.genreFacets ?? []) : [], - decades: hasQuery ? (facets?.decadeFacets ?? []) : [], - reviewedCount: hasQuery ? (facets?.reviewedCount ?? 0) : 0, + genres: facets?.genreFacets ?? [], + decades: facets?.decadeFacets ?? [], + reviewedCount: facets?.reviewedCount ?? 0, }, setGenres, setDecades, setReviewed, clearFilters, + resetSearch, sort: state.sort, setSort, search, hasQuery, - albums: hasQuery - ? edges.slice(0, pagination.visibleCount).map((edge) => edge.node) - : [], - totalCount: hasQuery ? (data?.searchAlbums.totalCount ?? 0) : 0, - loading: hasQuery && loading && networkStatus !== NetworkStatus.fetchMore, + albums: edges.slice(0, pagination.visibleCount).map((edge) => edge.node), + totalCount: data?.searchAlbums.totalCount ?? 0, + loading: loading && networkStatus !== NetworkStatus.fetchMore, loadingMore: pagination.loadingMore, pageError: pagination.pageError, hasNextPage, @@ -212,8 +214,8 @@ export function useAlbumSearch() { canLoadAutomatically, loadMoreAutomatically, // Refetch status distinguishes retries even when Apollo clears the previous error. - retrying: hasQuery && networkStatus === NetworkStatus.refetch, - error: hasQuery && Boolean(error), + retrying: networkStatus === NetworkStatus.refetch, + error: Boolean(error), retry, }; } diff --git a/client/src/hooks/useSearchState.test.ts b/client/src/hooks/useSearchState.test.ts index 503b157..64c8d8d 100644 --- a/client/src/hooks/useSearchState.test.ts +++ b/client/src/hooks/useSearchState.test.ts @@ -42,9 +42,10 @@ describe('parseSearchState', () => { }); 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); - expect(parseSearchState('?').sort).toBe(DEFAULT_SORT); + expect(parseSearchState('?sort=YEAR_DESC').sort).toBe('RELEASE_YEAR_DESC'); + expect(parseSearchState('?sort=').sort).toBe('RELEASE_YEAR_DESC'); + expect(parseSearchState('?').sort).toBe('RELEASE_YEAR_DESC'); + expect(parseSearchState('?q=blue&sort=YEAR_DESC').sort).toBe('RELEVANCE'); }); it('drops decades that are not integers', () => { @@ -81,9 +82,9 @@ describe('serializeSearchState', () => { }); it('writes only what differs from the default', () => { - expect(serializeSearchState({ ...EMPTY_SEARCH_STATE, q: 'blue' }, '')).toBe( - '?q=blue', - ); + expect( + serializeSearchState({ ...EMPTY_SEARCH_STATE, q: 'blue', sort: 'RELEVANCE' }, ''), + ).toBe('?q=blue'); expect(serializeSearchState({ ...EMPTY_SEARCH_STATE, sort: 'TITLE_ASC' }, '')).toBe( '?sort=TITLE_ASC', ); @@ -111,7 +112,7 @@ describe('serializeSearchState', () => { it('carries parameters it does not own through untouched', () => { const out = serializeSearchState( - { ...EMPTY_SEARCH_STATE, q: 'blue' }, + { ...EMPTY_SEARCH_STATE, q: 'blue', sort: 'RELEVANCE' }, '?utm_source=mail', ); expect(out).toContain('utm_source=mail'); @@ -131,6 +132,55 @@ describe('serializeSearchState', () => { }); describe('useSearchState', () => { + it('switches implicit defaults with the query and restores them from history', () => { + setUrl('/?genres=4&decades=1970&reviewed=1'); + const { result } = renderHook(() => useSearchState()); + expect(result.current.state.sort).toBe('RELEASE_YEAR_DESC'); + act(() => result.current.setQuery('blue')); + expect(result.current.state.sort).toBe('RELEVANCE'); + expect(window.location.search).toBe('?q=blue&genres=4&decades=1970&reviewed=1'); + act(() => result.current.setQuery(' ')); + expect(result.current.state).toEqual({ + ...EMPTY_SEARCH_STATE, + genres: ['4'], + decades: [1970], + reviewed: true, + }); + expect(window.location.search).toBe('?genres=4&decades=1970&reviewed=1'); + // Back and forward restore defaults from the URL without adding a sort parameter. + for (const [url, sort] of [ + ['/?q=blue&genres=4&decades=1970&reviewed=1', 'RELEVANCE'], + ['/?genres=4&decades=1970&reviewed=1', 'RELEASE_YEAR_DESC'], + ] as const) { + setUrl(url); + act(() => window.dispatchEvent(new PopStateEvent('popstate'))); + expect(result.current.state.sort).toBe(sort); + } + }); + + it.each(['RELEASE_YEAR_DESC', 'RELEVANCE', 'TITLE_ASC'] as const)( + 'keeps an explicit %s choice when switching between browsing and searching', + (sort) => { + setUrl('/?genres=4&decades=1970&reviewed=1'); + const { result } = renderHook(() => useSearchState()); + act(() => result.current.setSort(sort)); + expect(window.location.search).toBe( + '?sort=' + sort + '&genres=4&decades=1970&reviewed=1', + ); + for (const query of ['blue', '']) { + act(() => result.current.setQuery(query)); + expect(result.current.state).toEqual({ + q: query, + sort, + genres: ['4'], + decades: [1970], + reviewed: true, + }); + expect(new URLSearchParams(window.location.search).get('sort')).toBe(sort); + } + }, + ); + it('reads the URL on first render', () => { setUrl('/?q=blue&sort=TITLE_ASC'); const { result } = renderHook(() => useSearchState()); diff --git a/client/src/hooks/useSearchState.ts b/client/src/hooks/useSearchState.ts index 5cc7b3c..981a296 100644 --- a/client/src/hooks/useSearchState.ts +++ b/client/src/hooks/useSearchState.ts @@ -13,10 +13,11 @@ import { ALBUM_SORTS, type AlbumSort } from '../api/searchAlbums.js'; * * ?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 - * are preserved untouched, so adding one later cannot break a link someone - * already shared. + * Lists are one param per value. Implicit defaults are left out of the URL, + * so a plain search is just `?q=blue`. Explicit sort choices stay in the URL + * so switching between browsing and searching preserves them. Parameters this + * hook does not own are preserved untouched, so adding one later cannot break + * a link someone already shared. * * Paging is deliberately absent. #14 owns the cursor, and the contract is that * any change to these values drops it, so the cursor is never written to @@ -32,9 +33,13 @@ export interface SearchState { export const DEFAULT_SORT: AlbumSort = 'RELEVANCE'; +function defaultSort(q: string): AlbumSort { + return q.trim() ? DEFAULT_SORT : 'RELEASE_YEAR_DESC'; +} + export const EMPTY_SEARCH_STATE: SearchState = { q: '', - sort: DEFAULT_SORT, + sort: defaultSort(''), genres: [], decades: [], reviewed: false, @@ -84,13 +89,14 @@ function isGenreId(value: string): boolean { export function parseSearchState(search: string): SearchState { const params = new URLSearchParams(search); const sort = params.get(SEARCH_PARAMS.sort); + const q = (params.get(SEARCH_PARAMS.q) ?? '').trim(); const decades = parseValues(params, SEARCH_PARAMS.decades) .map(Number) .filter(Number.isInteger); return { - q: (params.get(SEARCH_PARAMS.q) ?? '').trim(), - sort: isAlbumSort(sort) ? sort : DEFAULT_SORT, + q, + sort: isAlbumSort(sort) ? sort : defaultSort(q), genres: parseValues(params, SEARCH_PARAMS.genres).filter(isGenreId), decades, reviewed: params.get(SEARCH_PARAMS.reviewed) === '1', @@ -99,10 +105,16 @@ export function parseSearchState(search: string): SearchState { /** * Write search state back into a query string. Params this hook does not own - * are carried over from `currentSearch` unchanged. + * are carried over from `currentSearch` unchanged. `explicitSort` keeps a new + * user choice even when it matches the current default. */ -export function serializeSearchState(state: SearchState, currentSearch: string): string { +export function serializeSearchState( + state: SearchState, + currentSearch: string, + explicitSort = false, +): string { const params = new URLSearchParams(currentSearch); + const keepSort = explicitSort || isAlbumSort(params.get(SEARCH_PARAMS.sort)); params.delete(SEARCH_PARAMS.q); params.delete(SEARCH_PARAMS.sort); @@ -112,7 +124,8 @@ export function serializeSearchState(state: SearchState, currentSearch: string): const q = state.q.trim(); if (q) params.set(SEARCH_PARAMS.q, q); - if (state.sort !== DEFAULT_SORT) params.set(SEARCH_PARAMS.sort, state.sort); + if (keepSort || state.sort !== defaultSort(q)) + params.set(SEARCH_PARAMS.sort, state.sort); // One param per value rather than a comma joined list. URLSearchParams // percent encodes a comma into `%2C`, which makes a shared link unreadable. // Genre ids are filtered here too, so the URL can never carry one the server @@ -166,9 +179,9 @@ function subscribe(listener: Listener): () => void { }; } -function writeSearchState(next: SearchState): void { +function writeSearchState(next: SearchState, explicitSort = false): void { const current = window.location.search; - const search = serializeSearchState(next, current); + const search = serializeSearchState(next, current, explicitSort); // No history entry when nothing actually changes. if (search === current) return; @@ -189,7 +202,13 @@ export function useSearchState() { const state = useSyncExternalStore(subscribe, readSearchState, readSearchState); const setSearch = useCallback((patch: Partial) => { - writeSearchState({ ...readSearchState(), ...patch }); + const next = { ...readSearchState(), ...patch }; + const sort = new URLSearchParams(window.location.search).get(SEARCH_PARAMS.sort); + // Only implicit defaults follow the query; a valid URL sort is a user choice. + if (patch.q !== undefined && patch.sort === undefined && !isAlbumSort(sort)) { + next.sort = defaultSort(next.q); + } + writeSearchState(next, patch.sort !== undefined); }, []); const setQuery = useCallback((q: string) => setSearch({ q }), [setSearch]); @@ -209,5 +228,19 @@ export function useSearchState() { [setSearch], ); - return { state, setQuery, setSort, setGenres, setDecades, setReviewed, clearFilters }; + const resetSearch = useCallback( + () => setSearch({ q: '', genres: [], decades: [], reviewed: false }), + [setSearch], + ); + + return { + state, + setQuery, + setSort, + setGenres, + setDecades, + setReviewed, + clearFilters, + resetSearch, + }; } diff --git a/client/src/pagination.test.tsx b/client/src/pagination.test.tsx index 8f3569b..6e0c1c4 100644 --- a/client/src/pagination.test.tsx +++ b/client/src/pagination.test.tsx @@ -22,6 +22,8 @@ import { const input: AlbumSearchInput = { query: 'record', sort: 'RELEVANCE' }; const searchChanges: [string, AlbumSearchInput][] = [ + ['/', { ...input, query: '', sort: 'RELEASE_YEAR_DESC' }], + ['/?genres=1', { ...input, query: '', sort: 'RELEASE_YEAR_DESC', genreIds: ['1'] }], ['?q=other', { ...input, query: 'other' }], ['?q=record&sort=TITLE_ASC', { ...input, sort: 'TITLE_ASC' }], ['?q=record&genres=1', { ...input, genreIds: ['1'] }], @@ -70,8 +72,9 @@ function page( function start( mocks: MockLink.MockedResponse[], + url = '/?q=record', ) { - window.history.replaceState({}, '', '/?q=record'); + window.history.replaceState({}, '', url); // Reuse the production policies, clearing cached results for each test. render( @@ -80,6 +83,17 @@ function start( ); } +// Waiting by title avoids repeatedly computing every card's accessible name +// while Apollo is trying to deliver a page. Keep the same role/name/visibility checks. +async function findAlbum(title: string) { + const link = await screen.findByText(title, { selector: '.album-card__link' }); + const article = link.closest('article'); + expect(article).toHaveRole('article'); + expect(article).toHaveAccessibleName(title); + expect(article).toBeVisible(); + return article; +} + async function navigate(query: string) { await act(async () => { window.history.pushState({}, '', query); @@ -126,6 +140,37 @@ function fullPage(last: number, searchInput = input) { } describe('cursor pagination', () => { + it.each([true, false])( + 'tabs to Back to top after the results controls when hasNextPage is %s', + async (hasNextPage) => { + vi.stubGlobal('scrollY', 601); + start([page('1', null, hasNextPage)]); + await findAlbum('Album 1'); + const top = screen.getByRole('button', { name: 'Back to top' }); + expect(screen.getAllByRole('button', { name: 'Back to top' })).toHaveLength(1); + expect(screen.getByRole('region', { name: 'Search results' })).toContainElement( + top, + ); + const user = userEvent.setup(); + const crate = screen.getByRole('button', { name: 'Add to crate' }); + crate.focus(); + await user.tab(); + if (hasNextPage) { + expect(screen.getByRole('button', { name: 'Load more' })).toHaveFocus(); + await user.tab(); + } else { + expect( + screen.queryByRole('button', { name: 'Load more' }), + ).not.toBeInTheDocument(); + } + expect(top).toHaveFocus(); + await user.tab({ shift: true }); + expect( + hasNextPage ? screen.getByRole('button', { name: 'Load more' }) : crate, + ).toHaveFocus(); + }, + ); + it.each(searchChanges)( 'returns from %s to 20 visible albums, reveals cached pages, then fetches page 5', async (url, changed) => { @@ -139,20 +184,22 @@ describe('cursor pagination', () => { return { ...mock, result: vi.fn(() => response), maxUsageCount: 3 }; }); start([...requests, page('other', null, false, changed)]); - await screen.findByRole('article', { name: 'Album 20' }); + await findAlbum('Album 20'); for (const last of [40, 60, 80]) { fireEvent.click(screen.getByRole('button', { name: 'Load more' })); - await screen.findByRole('article', { name: `Album ${last}` }); + await findAlbum(`Album ${last}`); } await navigate(url); - await screen.findByRole('article', { name: 'Album other' }); + await findAlbum('Album other'); await navigate('?q=record'); - expect(screen.getByRole('status')).toHaveTextContent('Showing 20 of 100 albums.'); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 20 of 100 matching albums.', + ); expect(screen.getAllByRole('article')).toHaveLength(20); for (const count of [40, 60]) { intersect(); expect(screen.getByRole('status')).toHaveTextContent( - `Showing ${count} of 100 albums.`, + `Showing ${count} of 100 matching albums.`, ); } intersect(); @@ -163,13 +210,15 @@ describe('cursor pagination', () => { fireEvent.click(button); fireEvent.click(button); }); - expect(screen.getByRole('status')).toHaveTextContent('Showing 80 of 100 albums.'); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 80 of 100 matching albums.', + ); for (const request of requests.slice(0, 4)) { expect(request.result).toHaveBeenCalledTimes(1); } expect(requests[4]!.result).not.toHaveBeenCalled(); fireEvent.click(button); - await screen.findByRole('article', { name: 'Album 100' }); + await findAlbum('Album 100'); expect(requests[4]!.result).toHaveBeenCalledTimes(1); expect(screen.getAllByRole('article')).toHaveLength(100); expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument(); @@ -190,7 +239,7 @@ describe('cursor pagination', () => { ]); fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); await navigate('?q=other'); - await screen.findByRole('article', { name: 'Album other' }); + await findAlbum('Album other'); await navigate('?q=record'); await act(() => new Promise((resolve) => setTimeout(resolve, 200))); expect(screen.getAllByRole('article')).toHaveLength(20); @@ -198,26 +247,42 @@ describe('cursor pagination', () => { expect(screen.getAllByRole('article')).toHaveLength(40); }); - it('stops automatic loading at 60 albums and allows subsequent manual pages', async () => { - const { intersect } = observeEnd(); - start([20, 40, 60, 80, 100].map((last) => fullPage(last))); - await screen.findByRole('article', { name: 'Album 20' }); - intersect(); - intersect(); // Repeated notifications must not consume another allowance. - await screen.findByRole('article', { name: 'Album 40' }); - intersect(); - await screen.findByRole('article', { name: 'Album 60' }); - intersect(); - expect(screen.getByRole('status')).toHaveTextContent('Showing 60 of 100 albums.'); - const button = screen.getByRole('button', { name: 'Load more' }); - expect(button).toHaveAttribute('aria-disabled', 'false'); - fireEvent.click(button); - await screen.findByRole('article', { name: 'Album 80' }); - intersect(); - expect(screen.getByRole('status')).toHaveTextContent('Showing 80 of 100 albums.'); - fireEvent.click(button); - await screen.findByRole('article', { name: 'Album 100' }); - }); + it.each(['record', ''])( + 'limits automatic loading and allows manual pages for query %j', + async (query) => { + const { intersect } = observeEnd(); + start( + [20, 40, 60, 80, 100].map((last) => + fullPage(last, { + ...input, + query, + sort: query ? 'RELEVANCE' : 'RELEASE_YEAR_DESC', + }), + ), + query ? '/?q=record' : '/', + ); + await findAlbum('Album 20'); + intersect(); + intersect(); // Repeated notifications must not consume another allowance. + await findAlbum('Album 40'); + intersect(); + await findAlbum('Album 60'); + intersect(); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 60 of 100 matching albums.', + ); + const button = screen.getByRole('button', { name: 'Load more' }); + expect(button).toHaveAttribute('aria-disabled', 'false'); + fireEvent.click(button); + await findAlbum('Album 80'); + intersect(); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 80 of 100 matching albums.', + ); + fireEvent.click(button); + await findAlbum('Album 100'); + }, + ); it.each(searchChanges)( 'resets the two-page automatic allowance for %s', @@ -231,21 +296,25 @@ describe('cursor pagination', () => { page('5', '4', true, changed), page('6', '5', true, changed), ]); - await screen.findByRole('article', { name: 'Album 1' }); + await findAlbum('Album 1'); intersect(); - await screen.findByRole('article', { name: 'Album 2' }); + await findAlbum('Album 2'); intersect(); - await screen.findByRole('article', { name: 'Album 3' }); + await findAlbum('Album 3'); intersect(); - expect(screen.getByRole('status')).toHaveTextContent('Showing 3 of 40 albums.'); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 3 of 40 matching albums.', + ); await navigate(url); - await screen.findByRole('article', { name: 'Album 4' }); + await findAlbum('Album 4'); intersect(); - await screen.findByRole('article', { name: 'Album 5' }); + await findAlbum('Album 5'); intersect(); - await screen.findByRole('article', { name: 'Album 6' }); + await findAlbum('Album 6'); intersect(); - expect(screen.getByRole('status')).toHaveTextContent('Showing 3 of 40 albums.'); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 3 of 40 matching albums.', + ); }, ); @@ -257,7 +326,7 @@ describe('cursor pagination', () => { expect(screen.getByRole('article', { name: 'Album 1' })).toBeInTheDocument(); expect(screen.getByRole('status')).toHaveTextContent('Loading more albums'); expect(button).toHaveFocus(); - await screen.findByRole('article', { name: 'Album 2' }); + await findAlbum('Album 2'); expect(screen.getAllByRole('article')).toHaveLength(2); expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument(); }); @@ -273,6 +342,11 @@ describe('cursor pagination', () => { const user = userEvent.setup(); screen.getByRole('button', { name: 'Search' }).focus(); + await user.tab(); + expect( + screen.getByRole('link', { name: 'Kevin McCutcheon on Unsplash' }), + ).toHaveFocus(); + // The filter panel's Filters button comes before the results. await user.tab(); expect(screen.getByRole('button', { name: 'Filters' })).toHaveFocus(); @@ -292,17 +366,21 @@ describe('cursor pagination', () => { // Browsers scroll a newly focused button into view, notifying the observer. intersect(); expect(button).toHaveAttribute('aria-disabled', 'false'); - expect(screen.getByRole('status')).toHaveTextContent('Showing 1 of 40 albums.'); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 1 of 40 matching albums.', + ); expect(result).not.toHaveBeenCalled(); await user.keyboard(key); expect(screen.getByRole('status')).toHaveTextContent('Loading more albums'); - await screen.findByRole('article', { name: 'Album 2' }); + await findAlbum('Album 2'); expect(result).toHaveBeenCalledTimes(1); expect(button).toHaveFocus(); intersect(); expect(button).toHaveAttribute('aria-disabled', 'false'); - expect(screen.getByRole('status')).toHaveTextContent('Showing 2 of 40 albums.'); + expect(screen.getByRole('status')).toHaveTextContent( + 'Showing 2 of 40 matching albums.', + ); }, ); @@ -317,7 +395,7 @@ describe('cursor pagination', () => { intersect(); fireEvent.click(button); }); - await screen.findByRole('article', { name: 'Album 2' }); + await findAlbum('Album 2'); expect(result).toHaveBeenCalledTimes(1); expect(disconnect).toHaveBeenCalled(); }); @@ -363,7 +441,7 @@ describe('cursor pagination', () => { ); expect(screen.getByRole('article', { name: 'Album 1' })).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Load more' })); - await screen.findByRole('article', { name: 'Album 2' }); + await findAlbum('Album 2'); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); }); @@ -376,10 +454,10 @@ describe('cursor pagination', () => { page('4', '3', false, changed), ]); fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); - await screen.findByRole('article', { name: 'Album 2' }); + await findAlbum('Album 2'); await navigate('?q=other'); fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); - await screen.findByRole('article', { name: 'Album 4' }); + await findAlbum('Album 4'); expect(screen.getAllByRole('article')).toHaveLength(2); expect(screen.getByRole('article', { name: 'Album 3' })).toBeInTheDocument(); expect(screen.queryByRole('article', { name: 'Album 1' })).not.toBeInTheDocument(); @@ -395,7 +473,7 @@ describe('cursor pagination', () => { ]); fireEvent.click(await screen.findByRole('button', { name: 'Load more' })); await navigate(url); - await screen.findByRole('article', { name: 'Album 3' }); + await findAlbum('Album 3'); await act(() => new Promise((resolve) => setTimeout(resolve, 150))); expect(screen.getAllByRole('article')).toHaveLength(1); expect(screen.queryByRole('article', { name: 'Album 2' })).not.toBeInTheDocument();