diff --git a/AGENTS.md b/AGENTS.md index 738dc86..057115b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ personal wantlist ("crate"). IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks`. -**Status: M4 delivered – final polish.** See the README's +**Status: Final submission ready (hand-in 27 November).** See the README's [feature overview](README.md#what-you-can-do-in-crate) for implemented features and the project status section for planned work. diff --git a/README.md b/README.md index 7d0d0f7..3a37762 100644 --- a/README.md +++ b/README.md @@ -11,12 +11,13 @@ IT2810 (NTNU) Project 2. Group T19: `erikhfj`, `robertky`, `evenkkl`, `rachelks` | | | | ------------------- | ---------------------------------------------------------- | -| Current milestone | **M4 delivered – final polish**, final hand-in 27 November | +| Current milestone | **Final submission ready**, hand-in 27 November | | Live prototype | http://it2810-19.idi.ntnu.no/project2 | | Architecture / ADRs | [`docs/architecture.md`](docs/architecture.md) | | Data model | [`docs/data-model.md`](docs/data-model.md) | | UI specification | [`docs/ui-specification.md`](docs/ui-specification.md) | | Scalability | [`docs/scalability.md`](docs/scalability.md) | +| Lighthouse & a11y | [`docs/lighthouse-results.md`](docs/lighthouse-results.md) | | Workflow | [`docs/WORKFLOW.md`](docs/WORKFLOW.md) | | AI usage log | [`docs/AI-USAGE.md`](docs/AI-USAGE.md) | | Running on the VM | [`docs/VM-setup.md`](docs/VM-setup.md) | @@ -190,7 +191,7 @@ only create noise in the stale-file check. ### End-to-end tests -`e2e/` holds Playwright tests that run in a real browser against a running stack. They cover one full journey (search, filter, sort, open an album, write a review, reload and find it again), case-insensitive search, a keyboard-only path from the skip link to a result, and axe-core scans of the main views. They expect the sample catalog from `db:seed`, so do not point them at the deployed MusicBrainz catalog. +`e2e/` holds Playwright tests that run in a real browser against a running stack. They cover a full search-to-review journey (`search.spec.ts`, including case-insensitive search, back-scroll/page restoration, search history, pagination, and review editing/validation), filter side-drawer keyboard focus and URL state (`filters.spec.ts`), crate persistence (`crate.spec.ts`, #134 / PR #137), a keyboard-only path from the skip link to a result, and real-browser axe-core WCAG 2.1 A/AA scans (`a11y.spec.ts`). They expect the sample catalog from `db:seed`, so do not point them at the deployed MusicBrainz catalog. ```bash pnpm --filter @t19/e2e exec playwright install chromium # once @@ -200,7 +201,7 @@ pnpm dev # client on :5173 pnpm test:e2e ``` -`E2E_BASE_URL` sets the client address (default `http://localhost:5173/project2/`). Run the tests against a separate database, since `db:seed` replaces the catalog. The journey writes its review as one fixed test user (`Listener 00000000`) and deletes the review at the end, so repeated runs leave a single `app_user` row and no reviews behind. +`E2E_BASE_URL` sets the client address (default `http://localhost:5173/project2/`). Run the tests against a separate database, since `db:seed` replaces the catalog. The journey writes its review using one fixed test user UUID (displayed under a deterministic SHA-256 music pseudonym rather than exposing the raw ID, `#100`) and cleans up its review and search history at the end, leaving a single `app_user` row and no stray reviews behind. ## Database seed data @@ -264,10 +265,16 @@ MusicBrainz release-group IDs, rather than bundled into the application. Cover availability is optional; albums without an ID or available artwork use the existing vinyl placeholder. The artwork attribution on the album detail page links to the corresponding MusicBrainz release-group page. Artwork rights remain -with their respective rights holders. +with their respective rights holders. Loading artwork directly in the browser +avoids hosting third-party images on the VM, with the privacy tradeoff that the +visitor's IP address is sent to Cover Art Archive / Internet Archive (Crate sets +`Referrer-Policy: no-referrer` so internal search URLs are not leaked; see +[architecture decisions](docs/architecture.md#7-security-privacy-and-deployment-tradeoffs)). -See [Lighthouse results](docs/lighthouse-results.md) for local production-preview -scores, artwork audit findings and the JavaScript bundle budget verified for #23. +See [Lighthouse and accessibility results](docs/lighthouse-results.md) for the +25 November local production-preview Lighthouse 13.6 scores across Discover, +Album detail, and Your crate (desktop & mobile, light & dark), production asset +sizes, and the zoom/reflow verification log. ### Catalog quality (#64) @@ -293,8 +300,10 @@ Remaining limitations: - 21 albums have no release year. They sort last and have no decade facet. - Names in non-Latin scripts (for example Mulatu Astatke as ሙላቱ አስታጥቄ) only match as written (Latin diacritics are normalized with PostgreSQL `unaccent`). -- Artists are matched by name, so two different artists with the same name - would share a row. None were found in the snapshot. +- Artists are matched by `musicBrainzArtistId` first and only fall back to + matching by name for existing rows that have no `musicBrainzArtistId` (such as + hand-seeded rows), preventing collisions between distinct MusicBrainz artists + that share a name. - Classical albums credit the composer as an artist, and compilations use "Various Artists", as MusicBrainz does. - Same title and artist is not always a duplicate: Color Humano released three @@ -341,80 +350,99 @@ for details. ## Accessibility -The interface supports keyboard navigation, visible focus indicators, labelled form controls and a skip link to the main content. Search results, loading states and errors provide feedback to assistive technologies. The layout adapts to smaller screens and respects reduced-motion preferences. +The interface supports keyboard navigation, visible focus indicators, labelled form controls, a modal filter side drawer with focus trapping, a manual Dark/Light theme toggle, and a skip link to the main content. Search results, loading states and errors provide feedback to assistive technologies. The layout adapts to smaller screens and respects reduced-motion preferences. -Automated accessibility tests use axe-core to check key search states, including initial, results, no-results and error views. Component tests also cover keyboard interactions and focus behavior. Since these tests run in jsdom, they cannot verify color contrast or layout. The Playwright tests therefore also run axe-core (WCAG 2.1 A and AA) in a real browser, where contrast is checked, and test a keyboard-only path with visible focus. Zoom and screen reader behavior are still tested manually. +Automated accessibility tests use axe-core in jsdom (covering search states, detail/review error states, and Your crate) and in a real Chromium browser via Playwright (`e2e/tests/a11y.spec.ts`, checking WCAG 2.1 A and AA including color contrast and keyboard focus). Real-browser axe-core checks (0 violations across 10 light/dark interactive states) and 200%/400% zoom (320 px viewport) reflow verification (0 px horizontal overflow) are logged in [Lighthouse and accessibility results](docs/lighthouse-results.md#accessibility-and-zoomreflow-verification), alongside the remaining manual screen-reader checklist. ## Sustainability measures -We consider sustainability through design choices that reduce unnecessary data transfer, processing and resource use, while acknowledging performance tradeoffs. - -| Measure | Resource consideration | Effect | -| ---------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| Plain CSS, no UI framework | No component-library runtime to download or parse | 0 UI dependencies in the bundle | -| `prefers-color-scheme` | OLED screens draw less power on a dark pixel | Dark theme when the OS asks for it | -| `prefers-reduced-motion` | Animations cost frames and battery | Collapsed to near-zero when the OS asks for it | -| Explicit search submission | Typing would otherwise cost one request per change | Typing sends no search requests; Search or Enter commits the query | -| `cache-first` fetch policy | A repeated search is already in the cache | No request when the complete requested result is cached | -| Cursor pagination and cached pages | Load only the next batch and reuse pages already fetched | 20 albums per page; 0 requests to reveal cached pages | -| Code-split album route | The detail page is not needed to browse search results | Separate detail chunks; see dated measurements below | -| Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | -| Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, but potentially higher query costs for broad prefixes | - -**Bundle size**, production build measured 24 November 2026: - -| File | Raw | Gzip | -| ----------------------- | --------: | --------: | -| `index-*.js` | 390.80 kB | 119.87 kB | -| `index-*.css` | 15.33 kB | 4.15 kB | -| `AlbumCover-*.js` | 55.01 kB | 13.56 kB | -| `AlbumCover-*.css` | 4.17 kB | 1.29 kB | -| `AlbumDetailPage-*.js` | 11.25 kB | 3.71 kB | -| `AlbumDetailPage-*.css` | 5.81 kB | 1.53 kB | -| `CratePage-*.js` | 2.32 kB | 0.99 kB | -| `CratePage-*.css` | 0.23 kB | 0.16 kB | -| `rolldown-runtime-*.js` | 0.58 kB | 0.36 kB | -| `index.html` | 0.78 kB | 0.38 kB | - -`AlbumDetailPage` and `CratePage` are code-split into separate lazy-loaded route chunks, so neither is loaded until the user opens an album or visits Your crate. `AlbumCover` is shared across views that render covers and is loaded eagerly on the initial Discover page (`App` → `ResultsLayout` → `AlbumCard`), so the first-page JavaScript payload is `index` + `AlbumCover` + `rolldown-runtime` (446.39 kB raw / 133.79 kB gzip) rather than `index` alone. Opening an album or crate page uses normal page navigation, while previously downloaded assets may be reused by the browser. Artwork is fetched separately from Cover Art Archive and is not included in these bundle sizes. Browser-native responsive images (`srcSet`/`sizes`) let the browser select an appropriate image size; card images load lazily, while detail artwork loads eagerly. - -**Requests for a typical search:** An uncached search initially fetches up to 20 albums in one `searchAlbums` request. Infinite scroll loads up to two additional pages automatically, while further pages are loaded using the Load more button. Previously fetched pages are reused from Apollo's cache without new GraphQL requests. No search requests are sent while the user types. Album artwork adds separate external image requests as cards approach the viewport. +We consider sustainability through design choices that reduce unnecessary data transfer, processing and resource use, while acknowledging performance and visual tradeoffs. + +| Measure | Resource consideration | Effect | +| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Plain CSS, no UI framework | No component-library runtime to download or parse | 0 UI dependencies in the bundle | +| Dark theme (`prefers-color-scheme` + manual toggle) | Dark surfaces (`#0a100d` / `#111914`) draw modestly less power on OLED than light mode (less than pure `#000`, minimal difference on LCD) | Follows OS preference by default; CSP-safe header toggle (`theme-init.js`, 298 B) persists manual override | +| `prefers-reduced-motion` | Animations cost frames and battery | Collapsed to near-zero when the OS asks for it | +| Zero-dependency SPA routing (#131) | Full-page reloads throw away cached GraphQL responses and re-parse the app | History API router preserves Apollo `InMemoryCache` across Discover, Album detail, and Your crate | +| Explicit search submission | Typing would otherwise cost one request per change | Typing sends no search requests; Search or Enter commits the query | +| `cache-first` fetch policy | A repeated search is already in the cache | No request when the complete requested result is cached | +| Cursor pagination and cached pages | Load only the next batch and reuse pages already fetched | 20 albums per page; 0 requests to reveal cached pages; Load more skips count/facet queries (#96) | +| Responsive hero WebP assets (#133) | Full-resolution desktop banners waste mobile bandwidth and slow LCP | `39.16 kB` desktop / `13.39 kB` mobile WebP (down from `449.87 kB`), lifting mobile Discover Lighthouse from 82 to 98 (mainly from `#133`) | +| Self-hosted WOFF2 + system Georgia | Third-party font CDNs add DNS/TLS round-trips and extra requests; shipping a third serif font costs bandwidth | Variable `DM Sans` and `Manrope` WOFF2 (`unicode-range` subsetted) stay same-origin; hero italic uses system `Georgia, serif` (0 B extra payload, trading minor cross-OS serif variation for zero bytes) | +| Code-split detail and crate routes | Detail and crate pages are not needed to browse search results | Separate lazy-loaded chunks; see dated measurements below | +| Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | +| Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, with higher query cost on broad prefixes | +| Apache compression & caching (#133) | Uncompressed JSON and uncached assets waste bandwidth on repeat visits | Configured to apply `mod_deflate` on `/graphql`, 1-year `immutable` caching on `/project2/assets/`, and `no-cache` on `index.html` and `theme-init.js` (see [`docs/VM-setup.md`](docs/VM-setup.md)) | + +**Production build sizes**, measured 26 November 2026 (`pnpm build`, Vite 8.3.8; decimal kB where `1 kB = 1,000 B`): + +| File | Raw | Gzip | +| --------------------------- | --------: | --------: | +| `index-*.js` | 395.38 kB | 121.47 kB | +| `CrateButton-*.js` | 59.02 kB | 14.52 kB | +| `AlbumDetailPage-*.js` | 13.85 kB | 4.43 kB | +| `CratePage-*.js` | 3.20 kB | 1.31 kB | +| `rolldown-runtime-*.js` | 0.59 kB | 0.36 kB | +| `theme-init.js` | 0.30 kB | 0.21 kB | +| `index-*.css` | 17.43 kB | 4.43 kB | +| `CrateButton-*.css` | 4.66 kB | 1.39 kB | +| `AlbumDetailPage-*.css` | 7.25 kB | 1.70 kB | +| `CratePage-*.css` | 0.23 kB | 0.16 kB | +| `index.html` | 0.97 kB | 0.44 kB | +| `favicon.svg` | 0.31 kB | 0.17 kB | +| `vinyl-hero-*.webp` | 39.16 kB | — | +| `vinyl-hero-mobile-*.webp` | 13.39 kB | — | +| `dm-sans-latin-*.woff2` | 36.93 kB | — | +| `dm-sans-latin-ext-*.woff2` | 18.22 kB | — | +| `manrope-latin-*.woff2` | 24.53 kB | — | +| `manrope-latin-ext-*.woff2` | 15.16 kB | — | + +`AlbumDetailPage` and `CratePage` are code-split into separate lazy-loaded route chunks, so neither is loaded until the user opens an album or visits Your crate. `CrateButton-*.js` holds the shared `CrateButton` and `AlbumCover` code loaded eagerly on the initial Discover page (`App` → `ResultsLayout` → `AlbumCard`), so the first-page JavaScript payload is `index` + `CrateButton` + `rolldown-runtime` + `theme-init.js` (**455.31 kB raw** / **136.56 kB gzip**). Navigating between Discover, Album detail, and Your crate uses client-side History API routing (`#131`), keeping previously loaded chunks and Apollo's `InMemoryCache` warm without full-page reloads. Artwork is fetched separately from Cover Art Archive and is not included in these bundle sizes. Browser-native responsive images (`srcSet`/`sizes` and ``) let the browser select an appropriate size; card images load lazily, while the hero backdrop and detail artwork load eagerly. + +**Requests for a typical search:** An uncached search initially fetches up to 20 albums in one `searchAlbums` request. Infinite scroll loads up to two additional pages automatically, while further pages are loaded using the Load more button (which omits count and facet queries, `#96`). Previously fetched pages are reused from Apollo's cache without new GraphQL requests. No search requests are sent while the user types. Album artwork adds separate external image requests as cards approach the viewport. + +## AI usage + +All AI tool usage, model versions, prompt-to-revision examples, and team reflections are logged in [`docs/AI-USAGE.md`](docs/AI-USAGE.md). ## Project status -| Milestone | Due | Delivers | -| --------- | ------ | ---------------------------------------------------------------------- | -| M1 | 2 Oct | Schema, data model, architecture, UI specification and workflow | -| M2 | 16 Oct | PostgreSQL and GraphQL backend on the VM, initial frontend interaction | -| M3 | 30 Oct | Search UI improvements, accessibility and sustainability | -| M4 | 13 Nov | Finished prototype and full test suite | +| Milestone | Due | Delivers | +| --------- | ------ | -------------------------------------------------------------------------------- | +| M1 | 2 Oct | Schema, data model, architecture, UI specification and workflow | +| M2 | 16 Oct | PostgreSQL and GraphQL backend on the VM, initial frontend interaction | +| M3 | 30 Oct | Search UI improvements, accessibility and sustainability | +| M4 | 13 Nov | Finished prototype and full test suite | +| Final | 27 Nov | Final submission: polished prototype, docs, live VM, Blackboard & FeedbackFruits | ### Where the code is -| Path | What it is | -| ---------------- | ----------------------------------------------------------- | -| `client/` | React, Vite and Apollo Client frontend | -| `server/` | GraphQL Yoga API and PostgreSQL database access | -| `schema.graphql` | GraphQL schema | -| `docs/` | Architecture, data model, UI, workflow, AI log and VM guide | +| Path | What it is | +| ---------------- | ----------------------------------------------------------------------------- | +| `client/` | React, Vite and Apollo Client frontend | +| `server/` | GraphQL Yoga API and PostgreSQL database access | +| `e2e/` | Playwright end-to-end and real-browser axe-core accessibility tests | +| `schema.graphql` | GraphQL schema | +| `docs/` | Architecture, data model, UI, scalability, Lighthouse/a11y, workflow, AI & VM | ## Try the application -Open http://it2810-19.idi.ntnu.no/project2/ or the local frontend and try these searches. Expected counts assume the 16-album sample catalog; other data may produce different results. +Open http://it2810-19.idi.ntnu.no/project2/ (or a local instance imported with `pnpm db:import:musicbrainz`) and try these searches against the 2,000-album MusicBrainz catalog: -| Search | Expected matches | Albums | -| ----------- | ---------------- | ------------------------------------------ | -| `blue` | 4 | Kind of Blue, Blue Train, Blue, Blue Lines | -| `coltrane` | 2 | A Love Supreme, Blue Train | -| `radiohead` | 2 | OK Computer, Kid A | +| Search | What to expect (2,000-album MusicBrainz catalog) | +| ------------ | --------------------------------------------------------------------------------- | +| `blue` | 66 matches including _Kind of Blue_ (Miles Davis) and _Thirteen Blue Magic Lane_ | +| `coltrane` | _A Love Supreme_ (John Coltrane, 1965) — prefix `coltr` matches the same | +| `pink floyd` | 2 matches: _The Dark Side of the Moon_ (1973) and _A Tree Full of Secrets_ (1999) | +| `kate bush` | _Hounds of Love_ (1985), with Cover Art Archive artwork and a 12-track tracklist | -Search is case-insensitive: `BLUE` should return the same matches as `blue`. +Search is case-insensitive (`BLUE` returns the same matches as `blue`). If you run locally against the 16-album `db:seed` sample catalog instead, expected counts and titles differ (for example, `blue` returns 4 sample albums). ## Infrastructure -PostgreSQL and the GraphQL API run directly on the group VM. Apache serves the frontend at http://it2810-19.idi.ntnu.no/project2/, falls back to `index.html` for client-side routes such as album pages, and proxies `/graphql` to the API on port 3001. The API runs as the `crate-api.service` systemd service. +PostgreSQL and the GraphQL API run directly on the group VM (`127.0.0.1:3001` by default). Apache serves the frontend at http://it2810-19.idi.ntnu.no/project2/, falls back to `index.html` for client-side routes such as `/project2/album/:id` and `/project2/crate`, proxies `/graphql` to the API, and is configured to apply gzip compression, immutable asset caching, and baseline HTTP security headers (see [VM setup](docs/VM-setup.md)). The API runs as the `crate-api.service` systemd service and is configured to run with `NODE_ENV=production` (see [VM setup](docs/VM-setup.md)). Note that the NTNU course VM serves traffic over plain HTTP rather than HTTPS; see [architecture decisions](docs/architecture.md#7-security-privacy-and-deployment-tradeoffs) for the transport tradeoff. -CI uses a self-hosted runner on the VM. Pushes to `main` run the project checks and deploy the frontend and backend. See [VM setup](docs/VM-setup.md) for deployment and verification steps. +CI uses a self-hosted runner on the VM. Pushes to `main` run the project checks (including PostgreSQL integration tests and Playwright E2E (#134, PR #137)) and deploy the frontend and backend. See [VM setup](docs/VM-setup.md) for deployment and verification steps. ## Contributing diff --git a/client/index.html b/client/index.html index 6010711..8567dc7 100644 --- a/client/index.html +++ b/client/index.html @@ -3,8 +3,11 @@ + + Crate — album catalog +
diff --git a/client/public/favicon.svg b/client/public/favicon.svg new file mode 100644 index 0000000..008254f --- /dev/null +++ b/client/public/favicon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/client/public/theme-init.js b/client/public/theme-init.js new file mode 100644 index 0000000..a6a6845 --- /dev/null +++ b/client/public/theme-init.js @@ -0,0 +1,10 @@ +(function () { + try { + var stored = window.localStorage.getItem('crate.theme'); + if (stored === 'light' || stored === 'dark') { + document.documentElement.dataset.theme = stored; + } + } catch { + // Ignore storage access errors; CSS media query handles system preference. + } +})(); diff --git a/client/src/App.css b/client/src/App.css index e29f8b7..ea71f12 100644 --- a/client/src/App.css +++ b/client/src/App.css @@ -34,11 +34,14 @@ gap: 2.5rem; } .navigation a { + display: inline-flex; + align-items: center; + min-height: 2.75rem; + padding-block: 0.4rem; text-decoration: none; } .navigation a[aria-current] { border-bottom: 2px solid var(--header-accent); - padding-block: 0.4rem; } .brand { font-family: var(--font-display); @@ -87,19 +90,27 @@ background: var(--bg); color: var(--text); } -.search-section::before, +.search-section__backdrop, .search-section::after { - content: ''; position: absolute; inset: 0; pointer-events: none; } -.search-section::before { +.search-section__backdrop { z-index: -2; - background: url('./assets/vinyl-hero.webp') center 22% / cover; + display: block; + overflow: hidden; +} +.search-section__backdrop-image { + display: block; + width: 100%; + height: 100%; + object-fit: cover; + object-position: center 45%; filter: saturate(0.5) contrast(1.03); } .search-section::after { + content: ''; z-index: -1; background: linear-gradient( @@ -141,13 +152,33 @@ font-size: 1.125rem; margin: 1.5rem 0 1.875rem; } +.hero-footer { + margin-top: 2rem; +} +.hero-jump-link { + display: none; + align-items: center; + gap: 0.35rem; + min-height: 2.75rem; + font-size: 0.9rem; + font-weight: 700; + color: var(--accent); + text-decoration: none; +} +.hero-jump-link:hover { + color: var(--accent-hover); + text-decoration: underline; + text-underline-offset: 0.2em; +} .hero-credit { - margin: 2rem 0 0; + margin: 0; color: var(--muted); font-size: 0.75rem; } .hero-credit a { - display: inline-block; + display: inline-flex; + align-items: center; + min-height: 2.75rem; padding-block: 0.25rem; text-underline-offset: 0.2em; } @@ -164,17 +195,6 @@ 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; @@ -189,13 +209,13 @@ .search-section { min-height: 0; align-items: end; - padding-block: 2.5rem 2rem; + padding-block: 1.5rem 1.25rem; } .search-section__content { padding-inline: 1rem; } - .search-section::before { - background-position: center 24%; + .search-section__backdrop-image { + object-position: center 40%; } .search-section::after { background: linear-gradient( @@ -205,11 +225,26 @@ rgba(5, 12, 8, 0.65) ); } + .search-section .eyebrow { + margin-bottom: 0.5rem; + } .search-section h1 { - font-size: clamp(2.5rem, 8vw, 3rem); + font-size: clamp(2rem, 8vw, 2.75rem); } .search-section .tagline { - font-size: 1rem; + font-size: 0.95rem; + margin: 0.75rem 0 1rem; + } + .hero-footer { + margin-top: 0.75rem; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem 1rem; + } + .hero-jump-link { + display: inline-flex; } } @media (max-width: 420px) { diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index b379e72..40d9a2f 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -417,6 +417,27 @@ describe('App search', () => { within(hero).getByText('Search, rate and collect albums you’ll want to return to.'), ).toBeInTheDocument(); expect(within(hero).getByRole('search')).toBeInTheDocument(); + const heroPicture = hero.querySelector('picture.search-section__backdrop'); + const heroSource = heroPicture?.querySelector('source'); + expect(heroSource).toHaveAttribute('media', '(max-width: 700px)'); + expect(heroSource).toHaveAttribute('srcset'); + expect(heroSource).not.toHaveAttribute('type'); + const heroImage = heroPicture?.querySelector('img'); + expect(heroImage).toHaveAttribute('src'); + expect(heroImage).toHaveAttribute('aria-hidden', 'true'); + expect(heroImage).toHaveAttribute('width', '1280'); + expect(heroImage).toHaveAttribute('height', '720'); + expect(heroImage).toHaveAttribute('loading', 'eager'); + expect(heroImage).toHaveAttribute('fetchpriority', 'high'); + expect(heroImage).toHaveAttribute('decoding', 'async'); + expect(heroImage).toHaveAttribute('alt', ''); + expect(heroImage).not.toHaveAttribute('srcset'); + expect(heroImage).not.toHaveAttribute('sizes'); + expect(within(hero).queryByRole('img')).not.toBeInTheDocument(); + expect(within(hero).getByRole('link', { name: 'Browse catalog' })).toHaveAttribute( + 'href', + '#catalogue', + ); expect(document.querySelector('a')).toBe( screen.getByRole('link', { name: 'Skip to content' }), ); diff --git a/client/src/App.tsx b/client/src/App.tsx index 4e76f6c..53bf63e 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -4,6 +4,7 @@ import { lazy, Suspense, useCallback, useEffect, useRef } from 'react'; import Link from './components/Link.js'; import RouteErrorBoundary from './components/RouteErrorBoundary.js'; +import ThemeToggle from './components/ThemeToggle.js'; import DiscoveryPage from './pages/DiscoveryPage.js'; import { appHref, stripBasePath, useLocation } from './router.js'; @@ -85,6 +86,7 @@ export default function App() { Your crate + diff --git a/client/src/assets/vinyl-hero-mobile.webp b/client/src/assets/vinyl-hero-mobile.webp new file mode 100644 index 0000000..f582919 Binary files /dev/null and b/client/src/assets/vinyl-hero-mobile.webp differ diff --git a/client/src/assets/vinyl-hero.LICENSE.md b/client/src/assets/vinyl-hero.LICENSE.md index e591d27..d4d3cf4 100644 --- a/client/src/assets/vinyl-hero.LICENSE.md +++ b/client/src/assets/vinyl-hero.LICENSE.md @@ -4,5 +4,7 @@ - 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. +- Local assets: + - `vinyl-hero.webp` (1280×720 landscape crop WebP, quality 78) + - `vinyl-hero-mobile.webp` (640×360 landscape crop WebP, quality 75) +- Used as a decorative responsive hero backdrop (`` / `` with `alt=""` and `aria-hidden="true"`) behind 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 index c37d591..ebb623f 100644 Binary files a/client/src/assets/vinyl-hero.webp and b/client/src/assets/vinyl-hero.webp differ diff --git a/client/src/components/AlbumCard.css b/client/src/components/AlbumCard.css index 3eba9a2..60b0d09 100644 --- a/client/src/components/AlbumCard.css +++ b/client/src/components/AlbumCard.css @@ -135,6 +135,11 @@ .album-card:focus-within .album-card__record { transform: scale(1.025); } +@media (hover: none), (pointer: coarse) { + .album-card__view { + display: none; + } +} @media (hover: hover) and (pointer: fine) { .album-card__view { opacity: 0; @@ -152,6 +157,27 @@ color: var(--accent); } } +/* Keep in sync with `@media (prefers-color-scheme: light)` below. */ +:root[data-theme='light'] .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); +} +:root[data-theme='light'] .album-card__cover { + background: var(--border); +} +/* Keep in sync with `:root[data-theme='light']` above. */ +@media (prefers-color-scheme: light) { + :root:not([data-theme='dark']) .album-card { + background: var(--surface); + border-radius: 3px; + box-shadow: inset 0 0 0 1px var(--border); + } + :root:not([data-theme='dark']) .album-card__cover { + background: var(--border); + } +} @media (prefers-reduced-motion: reduce) { .album-card .album-card__record, .album-card:hover .album-card__record, diff --git a/client/src/components/AlbumCard.test.tsx b/client/src/components/AlbumCard.test.tsx index 6d063b8..a3a0aee 100644 --- a/client/src/components/AlbumCard.test.tsx +++ b/client/src/components/AlbumCard.test.tsx @@ -39,7 +39,7 @@ it('handles nullable summary fields without inventing a rating or year', () => { ); expect(screen.getByText('Year unknown')).toBeInTheDocument(); expect(screen.getByText('Not yet rated')).toBeInTheDocument(); - expect(screen.getByText('0 reviews')).toBeInTheDocument(); + expect(screen.queryByText('0 reviews')).not.toBeInTheDocument(); expect(screen.getByRole('link', { name: 'Abbey Road' })).toHaveAttribute( 'href', `${import.meta.env.BASE_URL}album/1?q=Abbey&sort=TITLE_ASC`, @@ -130,7 +130,7 @@ it.each([false, true])( 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', + name: saved ? `Remove from crate: ${album.title}` : `Add to crate: ${album.title}`, }); expect(button.closest('a')).toBeNull(); const user = userEvent.setup(); @@ -165,7 +165,9 @@ it('reports crate mutation errors without navigating', async () => { , ); - await userEvent.setup().click(screen.getByRole('button', { name: 'Add to crate' })); + await userEvent + .setup() + .click(screen.getByRole('button', { name: `Add to crate: ${album.title}` })); expect(await screen.findByRole('alert')).toHaveTextContent( 'Could not update your crate', ); diff --git a/client/src/components/AlbumCard.tsx b/client/src/components/AlbumCard.tsx index ca06043..2a12b11 100644 --- a/client/src/components/AlbumCard.tsx +++ b/client/src/components/AlbumCard.tsx @@ -6,10 +6,17 @@ import AlbumCover from './AlbumCover.js'; import CrateButton from './CrateButton.js'; import Link from './Link.js'; -export default function AlbumCard({ album }: { album: AlbumSummary }) { +export default function AlbumCard({ + album, + onRemovedFromCrate, +}: { + album: AlbumSummary; + onRemovedFromCrate?: () => void; +}) { const location = useLocation(); const detailHref = appHref(`/album/${album.id}`, location.search); const rating = album.reviewCount > 0 ? album.averageRating : null; + const displayTitle = album.title || 'Untitled album'; return (
@@ -53,16 +60,18 @@ export default function AlbumCard({ album }: { album: AlbumSummary }) {

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

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

-

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

+ {album.reviewCount > 0 && ( +

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

+ )}
{album.genres.length > 0 ? (
    @@ -73,7 +82,13 @@ export default function AlbumCard({ album }: { album: AlbumSummary }) { ) : (

    Genre unknown

    )} - +
diff --git a/client/src/components/AlbumCover.css b/client/src/components/AlbumCover.css index 40da2d0..c3403d5 100644 --- a/client/src/components/AlbumCover.css +++ b/client/src/components/AlbumCover.css @@ -12,7 +12,7 @@ inset: 0; width: 100%; height: 100%; - object-fit: contain; + object-fit: cover; background: var(--surface-raised); } .album-card__record { diff --git a/client/src/components/AlbumCover.test.tsx b/client/src/components/AlbumCover.test.tsx index a049bb1..3a95021 100644 --- a/client/src/components/AlbumCover.test.tsx +++ b/client/src/components/AlbumCover.test.tsx @@ -32,6 +32,7 @@ it('uses responsive thumbnails and native loading with decorative semantics', () expect(image).toHaveAttribute('loading', 'lazy'); expect(image).not.toHaveAttribute('fetchpriority'); expect(image).toHaveAttribute('decoding', 'async'); + expect(image).toHaveAttribute('referrerpolicy', 'no-referrer'); expect(image).toHaveAttribute('alt', ''); expect(screen.queryByRole('img')).not.toBeInTheDocument(); }); @@ -53,6 +54,7 @@ it('loads detail artwork eagerly with 500px and 1200px thumbnails', () => { expect(image).toHaveAttribute('loading', 'eager'); expect(image).toHaveAttribute('fetchpriority', 'high'); expect(image).toHaveAttribute('decoding', 'async'); + expect(image).toHaveAttribute('referrerpolicy', 'no-referrer'); expect(image).toHaveAttribute('alt', ''); expect(screen.queryByRole('img')).not.toBeInTheDocument(); }); diff --git a/client/src/components/AlbumCover.tsx b/client/src/components/AlbumCover.tsx index 86aa734..ba0ce3f 100644 --- a/client/src/components/AlbumCover.tsx +++ b/client/src/components/AlbumCover.tsx @@ -36,6 +36,7 @@ export default function AlbumCover({ loading={variant === 'detail' ? 'eager' : 'lazy'} fetchPriority={variant === 'detail' ? 'high' : undefined} decoding="async" + referrerPolicy="no-referrer" alt="" onLoad={() => onLoadChange?.(true)} onError={() => { diff --git a/client/src/components/CrateButton.test.tsx b/client/src/components/CrateButton.test.tsx index 0bd57ea..ae35dd9 100644 --- a/client/src/components/CrateButton.test.tsx +++ b/client/src/components/CrateButton.test.tsx @@ -27,16 +27,25 @@ function CrateViews() { return ( <>
- +
- +
); } -it('keeps list and detail crate controls in sync after add and remove', async () => { +it('keeps list and detail crate controls in sync with unique action labels and no double state announcement', async () => { const { container } = render( { + render( + +
+ + +
+
, + ); + expect( + screen.getByRole('button', { name: 'Add to crate: Abbey Road' }), + ).toBeInTheDocument(); + expect( + screen.getByRole('button', { name: 'Remove from crate: Blue' }), + ).toBeInTheDocument(); }); it('retains focus through repeated toggles and ignores activation while a mutation is pending', async () => { @@ -154,7 +178,7 @@ it('retains focus through repeated toggles and ignores activation while a mutati
, ); const [button, regularButton] = await screen.findAllByRole('button', { - name: 'Add to crate', + name: 'Add to crate: Abbey Road', }); const user = userEvent.setup(); await user.tab(); @@ -166,17 +190,19 @@ it('retains focus through repeated toggles and ignores activation while a mutati expect(button).not.toBeDisabled(); expect(button).toHaveFocus(); await user.keyboard('{Enter} '); - await waitFor(() => expect(button).toHaveAttribute('aria-pressed', 'true')); + await waitFor(() => + expect(button).toHaveAccessibleName('Remove from crate: Abbey Road'), + ); 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')); + await waitFor(() => expect(button).toHaveAccessibleName('Add to crate: Abbey Road')); expect(removeResult).toHaveBeenCalledTimes(1); - expect(button).toHaveAccessibleName('Add to crate'); expect(button).toHaveFocus(); await user.keyboard(' '); - await waitFor(() => expect(button).toHaveAttribute('aria-pressed', 'true')); + await waitFor(() => + expect(button).toHaveAccessibleName('Remove from crate: Abbey Road'), + ); expect(addResult).toHaveBeenCalledTimes(2); expect(button).toHaveFocus(); await user.tab(); @@ -184,3 +210,71 @@ it('retains focus through repeated toggles and ignores activation while a mutati await user.tab({ shift: true }); expect(button).toHaveFocus(); }); + +it('announces crate additions and removals via a visually hidden status live region', async () => { + const { rerender } = render( + + + , + ); + + expect(screen.queryByRole('status')).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Add to crate: Abbey Road' })); + const addedStatus = await screen.findByRole('status'); + expect(addedStatus).toHaveTextContent('Added Abbey Road to your crate.'); + expect(addedStatus).toHaveClass('visually-hidden'); + expect(addedStatus).toHaveAttribute('aria-live', 'polite'); + + rerender( + + + , + ); + + fireEvent.click(screen.getByRole('button', { name: 'Remove from crate: Abbey Road' })); + await waitFor(() => + expect(screen.getByRole('status')).toHaveTextContent( + 'Removed Abbey Road from your crate.', + ), + ); +}); diff --git a/client/src/components/CrateButton.tsx b/client/src/components/CrateButton.tsx index 1a2ec37..1193f7e 100644 --- a/client/src/components/CrateButton.tsx +++ b/client/src/components/CrateButton.tsx @@ -5,11 +5,24 @@ import { useMutation } from '@apollo/client/react'; import { ADD_TO_CRATE, REMOVE_FROM_CRATE } from '../api/crate.js'; -type Props = { albumId: string; isInCrate: boolean; compact?: boolean }; +type Props = { + albumId: string; + albumTitle?: string; + isInCrate: boolean; + compact?: boolean; + onRemoved?: () => void; +}; -export default function CrateButton({ albumId, isInCrate, compact = false }: Props) { +export default function CrateButton({ + albumId, + albumTitle, + isInCrate, + compact = false, + onRemoved, +}: Props) { const mutationInFlight = useRef(false); const [error, setError] = useState(null); + const [announcement, setAnnouncement] = useState(null); const [addToCrate, addState] = useMutation(ADD_TO_CRATE, { update(cache, { data }) { const savedAlbum = data?.addToCrate.album; @@ -31,17 +44,29 @@ export default function CrateButton({ albumId, isInCrate, compact = false }: Pro }, }); const busy = addState.loading || removeState.loading; + const visibleLabel = isInCrate ? 'Remove from crate' : 'Add to crate'; + const accessibleLabel = albumTitle ? `${visibleLabel}: ${albumTitle}` : visibleLabel; 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); + setAnnouncement(null); try { if (isInCrate) { await removeFromCrate({ variables: { albumId } }); + setAnnouncement( + albumTitle + ? `Removed ${albumTitle} from your crate.` + : 'Removed from your crate.', + ); + onRemoved?.(); } else { await addToCrate({ variables: { albumId } }); + setAnnouncement( + albumTitle ? `Added ${albumTitle} to your crate.` : 'Added to your crate.', + ); } } catch (caught) { console.error('Could not update crate:', caught); @@ -56,8 +81,7 @@ export default function CrateButton({ albumId, isInCrate, compact = false }: Pro + {announcement && ( + + {announcement} + + )} {error && ( {error} diff --git a/client/src/components/FilterPanel.css b/client/src/components/FilterPanel.css index 059c7a0..2eecdb8 100644 --- a/client/src/components/FilterPanel.css +++ b/client/src/components/FilterPanel.css @@ -147,19 +147,19 @@ } .active-filters button { max-width: 100%; - min-height: 2rem; - padding: 0.25rem 0.625rem; + min-height: 2.75rem; + padding: 0.5rem 0.875rem; border: 1px solid var(--border-strong); border-radius: 100px; background: var(--chip-bg); color: var(--chip-text); - font-size: 0.8rem; + font-size: 0.8125rem; overflow-wrap: anywhere; } .clear-filters, .show-filter-options { - min-height: 2rem; - padding: 0.25rem 0.625rem; + min-height: 2.75rem; + padding: 0.5rem 0.875rem; font-size: 0.8125rem; } .show-filter-options { diff --git a/client/src/components/ReviewForm.css b/client/src/components/ReviewForm.css index 91985af..6cc01b4 100644 --- a/client/src/components/ReviewForm.css +++ b/client/src/components/ReviewForm.css @@ -75,15 +75,35 @@ margin: 0.4rem 0 0; text-align: right; } +.review-form__error, +.review-form__refresh-error p { + color: var(--danger); + font-weight: 500; +} +.review-form__error { + margin: 0.75rem 0 0; +} .review-form__refresh-error { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem 0.75rem; + margin-top: 0.75rem; } .review-form__refresh-error p { margin: 0; } +.review-form__delete-confirm { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; +} +.review-form__delete-prompt { + font-size: 0.875rem; + font-weight: 600; + color: var(--danger); +} .review-form__actions { display: flex; flex-wrap: wrap; diff --git a/client/src/components/ReviewForm.test.tsx b/client/src/components/ReviewForm.test.tsx index b49e6ab..8d2db87 100644 --- a/client/src/components/ReviewForm.test.tsx +++ b/client/src/components/ReviewForm.test.tsx @@ -1,3 +1,4 @@ +import { CombinedGraphQLErrors } from '@apollo/client/errors'; import { MockedProvider } from '@apollo/client/testing/react'; import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { expect, it, vi } from 'vitest'; @@ -8,17 +9,28 @@ import axe from 'axe-core'; import { DELETE_REVIEW, UPSERT_REVIEW } from '../api/reviews.js'; import ReviewForm from './ReviewForm.js'; -it('requires an accessible 1 to 5 star choice before it saves', () => { - render( +it('requires an accessible 1 to 5 star choice before it saves, links the error, and moves focus', async () => { + const { container } = render( - +
+ +
, ); fireEvent.click(screen.getByRole('button', { name: 'Publish review' })); - expect(screen.getByRole('alert')).toHaveTextContent( - 'Choose a rating from 1 to 5 stars', + const alert = screen.getByRole('alert'); + expect(alert).toHaveTextContent('Choose a rating from 1 to 5 stars'); + expect(alert).toHaveAttribute('id', 'review-form-error'); + expect(alert).toHaveClass('review-form__error'); + + const ratingGroup = screen.getByRole('radiogroup', { name: 'Rating' }); + expect(ratingGroup).toHaveAttribute('aria-invalid', 'true'); + expect(ratingGroup).toHaveAttribute( + 'aria-describedby', + 'review-rating-hint review-form-error', ); + expect(screen.getByRole('radio', { name: '1 star' })).toHaveFocus(); expect(screen.getAllByRole('radio')).toHaveLength(5); expect(screen.getByRole('radio', { name: '5 stars' })).not.toBeChecked(); expect(screen.getByRole('textbox', { name: /comment/i })).toHaveAttribute( @@ -30,6 +42,16 @@ it('requires an accessible 1 to 5 star choice before it saves', () => { 'aria-describedby', 'review-comment-counter', ); + + const audit = await axe.run(container, { + rules: { 'color-contrast': { enabled: false } }, + }); + expect(audit.violations.map((v) => v.id)).toEqual([]); + + // Selecting a rating clears the validation error and aria-invalid state. + fireEvent.click(screen.getByRole('radio', { name: '4 stars' })); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + expect(ratingGroup).not.toHaveAttribute('aria-invalid'); }); it('updates the character counter without announcing every keystroke', () => { @@ -161,7 +183,7 @@ it('uses native radio keyboard navigation and exposes the selected rating', asyn const two = screen.getByRole('radio', { name: '2 stars' }); expect(two).toBeChecked(); expect(two).toHaveFocus(); - expect(screen.getByRole('group', { name: 'Rating' })).toHaveAccessibleDescription( + expect(screen.getByRole('radiogroup', { name: 'Rating' })).toHaveAccessibleDescription( '2 out of 5 stars', ); await user.tab(); @@ -237,7 +259,7 @@ it('blocks unchanged saves and updates availability when edits are reverted', as expect(requested).not.toHaveBeenCalled(); }); -it('deletes an existing review and clears the form', async () => { +it('requires accessible confirmation before deleting an existing review and supports Escape cancel', async () => { let finishRefresh!: () => void; const refresh = new Promise((resolve) => { finishRefresh = resolve; @@ -251,7 +273,7 @@ it('deletes an existing review and clears the form', async () => { }, }, })); - render( + const { container } = render( { }, ]} > - +
+ +
, ); const user = userEvent.setup(); - const button = screen.getByRole('button', { name: 'Delete review' }); - button.focus(); + const deleteButton = screen.getByRole('button', { name: 'Delete review' }); + deleteButton.focus(); + await user.keyboard('{Enter}'); + + // Confirmation prompt appears without firing the delete mutation yet. + expect(result).not.toHaveBeenCalled(); + expect(screen.getByText('Delete your review?')).toBeInTheDocument(); + const cancelButton = screen.getByRole('button', { name: 'Cancel' }); + await waitFor(() => expect(cancelButton).toHaveFocus()); + + const audit = await axe.run(container, { + rules: { 'color-contrast': { enabled: false } }, + }); + expect(audit.violations.map((v) => v.id)).toEqual([]); + + // Escape inside the textarea must not dismiss confirmation or hijack focus. + const commentBox = screen.getByRole('textbox'); + commentBox.focus(); + await user.keyboard('{Escape}'); + expect(commentBox).toHaveFocus(); + expect(screen.getByRole('button', { name: 'Confirm delete' })).toBeInTheDocument(); + + // Escape inside the confirmation group cancels it and restores focus to Delete review. + cancelButton.focus(); + await user.keyboard('{Escape}'); + expect( + screen.queryByRole('button', { name: 'Confirm delete' }), + ).not.toBeInTheDocument(); + await waitFor(() => + expect(screen.getByRole('button', { name: 'Delete review' })).toHaveFocus(), + ); + expect(result).not.toHaveBeenCalled(); + + // Confirming proceeds with deletion. + await user.keyboard('{Enter}'); + const confirmButton = screen.getByRole('button', { name: 'Confirm delete' }); + confirmButton.focus(); await user.keyboard('{Enter}'); await waitFor(() => expect(onChanged).toHaveBeenCalledOnce()); - expect(button).toHaveFocus(); - expect(button).not.toBeDisabled(); - expect(button).toHaveAttribute('aria-disabled', 'true'); + expect(confirmButton).toHaveFocus(); + expect(confirmButton).not.toBeDisabled(); + expect(confirmButton).toHaveAttribute('aria-disabled', 'true'); await user.keyboard(' '); - fireEvent.submit(button.closest('form')!); + fireEvent.submit(confirmButton.closest('form')!); await act(async () => finishRefresh()); const status = await screen.findByRole('status'); expect(status).toHaveTextContent('Your review was deleted.'); await waitFor(() => expect(status).toHaveFocus()); expect(onChanged).toHaveBeenCalledOnce(); expect(result).toHaveBeenCalledOnce(); - expect(button).toHaveAttribute('aria-disabled', 'false'); expect(screen.queryByRole('alert')).not.toBeInTheDocument(); expect(screen.getByRole('textbox')).toHaveValue(''); expect(screen.queryByRole('radio', { checked: true })).not.toBeInTheDocument(); @@ -362,6 +420,9 @@ it.each(['publish', 'update', 'delete'])( : 'Delete review', }); fireEvent.click(actionButton); + if (action === 'delete') { + fireEvent.click(screen.getByRole('button', { name: 'Confirm delete' })); + } expect(await screen.findByRole('status')).toHaveTextContent( action === 'publish' @@ -375,12 +436,24 @@ it.each(['publish', 'update', 'delete'])( ? 'Your review was deleted, but album details could not be refreshed.' : `${action === 'publish' ? 'Your review was published.' : 'Your review was updated.'} Album details could not be refreshed.`, ); - expect(screen.getByRole('button', { name: 'Retry album refresh' })).toBeVisible(); + const retryButton = screen.getByRole('button', { name: 'Retry album refresh' }); + expect(retryButton).toBeVisible(); + if (action === 'delete') { + await waitFor(() => expect(retryButton).toHaveFocus()); + } // Activating the aria-disabled submit/delete control must not re-fire the mutation. - expect(actionButton).toHaveAttribute('aria-disabled', 'true'); - fireEvent.click(actionButton); - if (action !== 'delete') fireEvent.submit(actionButton.closest('form')!); + const disabledAction = screen.getByRole('button', { + name: + action === 'publish' + ? 'Publish review' + : action === 'update' + ? 'Save changes' + : 'Delete review', + }); + expect(disabledAction).toHaveAttribute('aria-disabled', 'true'); + fireEvent.click(disabledAction); + if (action !== 'delete') fireEvent.submit(disabledAction.closest('form')!); expect(result).toHaveBeenCalledOnce(); fireEvent.click(screen.getByRole('button', { name: 'Retry album refresh' })); @@ -466,7 +539,8 @@ it.each(['publish', 'update', 'delete'])( ); fireEvent.click(screen.getByRole('radio', { name: '4 stars' })); fireEvent.change(screen.getByRole('textbox'), { target: { value: 'My review' } }); - const button = screen.getByRole('button', { + const user = userEvent.setup(); + let button = screen.getByRole('button', { name: action === 'publish' ? 'Publish review' @@ -474,10 +548,20 @@ it.each(['publish', 'update', 'delete'])( ? 'Save changes' : 'Delete review', }); - const user = userEvent.setup(); + if (action === 'delete') { + fireEvent.click(button); + button = screen.getByRole('button', { name: 'Confirm delete' }); + } button.focus(); await user.keyboard('{Enter}'); - expect(await screen.findByRole('alert')).toHaveTextContent('Offline'); + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent( + action === 'delete' + ? 'Your review could not be deleted. Please try again.' + : 'Your review could not be saved. Please try again.', + ); + expect(alert).not.toHaveTextContent('Offline'); + expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-invalid'); expect(button).toHaveFocus(); expect(button).not.toBeDisabled(); expect(button).toHaveAttribute('aria-disabled', 'false'); @@ -498,3 +582,52 @@ it.each(['publish', 'update', 'delete'])( expect(screen.queryByRole('alert')).not.toBeInTheDocument(); }, ); + +it('marks the comment textarea invalid only for comment validation errors', async () => { + const request = { + query: UPSERT_REVIEW, + variables: { input: { albumId: '1', rating: 4, comment: 'Too long' } }, + }; + render( + + {})} /> + , + ); + + fireEvent.click(screen.getByRole('radio', { name: '4 stars' })); + fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Too long' } }); + const submitButton = screen.getByRole('button', { name: 'Publish review' }); + + // Non-comment GraphQL error must not mark the comment textarea invalid. + fireEvent.click(submitButton); + expect(await screen.findByRole('alert')).toHaveTextContent('Album not found.'); + const textbox = screen.getByRole('textbox'); + expect(textbox).not.toHaveAttribute('aria-invalid'); + expect(textbox).toHaveAttribute('aria-describedby', 'review-comment-counter'); + + // Comment validation error marks the textarea invalid and links the alert. + fireEvent.click(submitButton); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Comment must be 2000 characters or fewer.', + ); + expect(textbox).toHaveAttribute('aria-invalid', 'true'); + expect(textbox).toHaveAttribute( + 'aria-describedby', + 'review-comment-counter review-form-error', + ); +}); diff --git a/client/src/components/ReviewForm.tsx b/client/src/components/ReviewForm.tsx index b386e8c..367da78 100644 --- a/client/src/components/ReviewForm.tsx +++ b/client/src/components/ReviewForm.tsx @@ -1,6 +1,7 @@ import './ReviewForm.css'; import { useEffect, useRef, useState } from 'react'; +import { CombinedGraphQLErrors } from '@apollo/client/errors'; import { useMutation } from '@apollo/client/react'; import { @@ -11,6 +12,19 @@ import { type ExistingReview = { id: string; rating: number; comment: string } | null; const MAX_COMMENT_LENGTH = 2000; +const REVIEW_ERROR_ID = 'review-form-error'; +const SAFE_VALIDATION_MESSAGE = + /^(Rating must be|Comment must be|Album not found|Review not found)/i; + +function formatReviewError(caught: unknown, fallback: string): string { + if (CombinedGraphQLErrors.is(caught)) { + const safeMessage = caught.errors + .map((item) => item.message.trim()) + .find((message) => SAFE_VALIDATION_MESSAGE.test(message)); + if (safeMessage) return safeMessage; + } + return fallback; +} interface Props { albumId: string; @@ -22,10 +36,18 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) { const [rating, setRating] = useState(review?.rating ?? 0); const [comment, setComment] = useState(review?.comment ?? ''); const [error, setError] = useState(null); + const [ratingError, setRatingError] = useState(false); const [refreshError, setRefreshError] = useState(null); const [status, setStatus] = useState(null); const [busy, setBusy] = useState(false); + const [confirmingDelete, setConfirmingDelete] = useState(false); const statusRef = useRef(null); + const retryRefreshRef = useRef(null); + const focusRetryRefreshRef = useRef(false); + const firstStarRef = useRef(null); + const deleteButtonRef = useRef(null); + const cancelDeleteRef = useRef(null); + const restoreDeleteFocusRef = useRef(false); // Block repeated activations before React renders the busy state. const mutationInFlight = useRef(false); const [saveReview] = useMutation(UPSERT_REVIEW, { @@ -47,32 +69,72 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) { review !== null && rating === review.rating && comment.trim() === review.comment; useEffect(() => { + if (refreshError && focusRetryRefreshRef.current) { + focusRetryRefreshRef.current = false; + retryRefreshRef.current?.focus(); + return; + } if (status) statusRef.current?.focus(); - }, [status]); + }, [status, refreshError]); + + useEffect(() => { + if (confirmingDelete) { + cancelDeleteRef.current?.focus(); + return; + } + if (restoreDeleteFocusRef.current) { + restoreDeleteFocusRef.current = false; + deleteButtonRef.current?.focus(); + } + }, [confirmingDelete]); function announce(message: string) { setStatus(message); } + function requestDelete() { + if (!review || busy || Boolean(refreshError) || mutationInFlight.current) return; + setError(null); + setRatingError(false); + setConfirmingDelete(true); + } + + function cancelDelete() { + if (busy) return; + restoreDeleteFocusRef.current = true; + setConfirmingDelete(false); + } + + function handleConfirmDeleteKeyDown(event: React.KeyboardEvent) { + if (event.key === 'Escape' && !busy) { + event.preventDefault(); + cancelDelete(); + } + } + async function submit(event: React.FormEvent) { event.preventDefault(); if (mutationInFlight.current || unchanged || refreshError) return; if (rating < 1 || rating > 5) { setError('Choose a rating from 1 to 5 stars.'); + setRatingError(true); + firstStarRef.current?.focus(); return; } mutationInFlight.current = true; setBusy(true); setError(null); + setRatingError(false); setRefreshError(null); setStatus(null); + setConfirmingDelete(false); try { try { await saveReview({ variables: { input: { albumId, rating, comment } } }); } catch (caught) { setError( - caught instanceof Error ? caught.message : 'Your review could not be saved.', + formatReviewError(caught, 'Your review could not be saved. Please try again.'), ); return; } @@ -100,6 +162,7 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) { mutationInFlight.current = true; setBusy(true); setError(null); + setRatingError(false); setRefreshError(null); setStatus(null); try { @@ -107,7 +170,10 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) { await deleteReview({ variables: { id: review.id } }); } catch (caught) { setError( - caught instanceof Error ? caught.message : 'Your review could not be deleted.', + formatReviewError( + caught, + 'Your review could not be deleted. Please try again.', + ), ); return; } @@ -116,8 +182,11 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) { setComment(''); try { await onChanged(); + setConfirmingDelete(false); announce('Your review was deleted.'); } catch { + setConfirmingDelete(false); + focusRetryRefreshRef.current = true; setRefreshError( 'Your review was deleted, but album details could not be refreshed. Try again to update them.', ); @@ -145,6 +214,16 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) { } } + const ratingHasError = + ratingError || Boolean(error && error.startsWith('Rating must be')); + const commentHasError = Boolean(error && error.startsWith('Comment must be')); + const ratingDescribedBy = ratingHasError + ? `review-rating-hint ${REVIEW_ERROR_ID}` + : 'review-rating-hint'; + const commentDescribedBy = commentHasError + ? `review-comment-counter ${REVIEW_ERROR_ID}` + : 'review-comment-counter'; + return (

{review ? 'Update your review' : 'Write a review'}

Rating
@@ -164,12 +245,19 @@ export default function ReviewForm({ albumId, review, onChanged }: Props) { className={value <= rating ? 'review-form__star--filled' : undefined} > setRating(value)} + onChange={() => { + setRating(value); + if (ratingError) { + setRatingError(false); + setError(null); + } + }} />

{comment.length.toLocaleString('en-US')} /{' '} {MAX_COMMENT_LENGTH.toLocaleString('en-US')} characters

- {error &&

{error}

} + {error && ( + + )} {refreshError && (

{refreshError}

- {review && ( - - )} + {review && + (confirmingDelete ? ( +
+ Delete your review? + + +
+ ) : ( + + ))}
); diff --git a/client/src/components/SearchForm.css b/client/src/components/SearchForm.css index 7be5961..3fb428f 100644 --- a/client/src/components/SearchForm.css +++ b/client/src/components/SearchForm.css @@ -60,6 +60,20 @@ .search-form__icon { display: none; } + .search-form { + padding: 0.375rem; + gap: 0.375rem; + } + .search-form input { + min-height: 2.75rem; + padding: 0.5rem 0.75rem; + } + .search-form button { + min-height: 2.75rem; + padding: 0.5rem 1.125rem; + } +} +@media (max-width: 22.5rem) { .search-form { flex-direction: column; align-items: stretch; diff --git a/client/src/components/SearchForm.test.tsx b/client/src/components/SearchForm.test.tsx index 0fdd149..5996f43 100644 --- a/client/src/components/SearchForm.test.tsx +++ b/client/src/components/SearchForm.test.tsx @@ -36,7 +36,7 @@ describe('SearchForm', () => { ); const input = screen.getByRole('combobox', { name: 'Search by album or artist' }); act(() => input.focus()); - fireEvent.change(input, { target: { value: 'Unsubmitted' } }); + fireEvent.change(input, { target: { value: 'Blu' } }); fireEvent.keyDown(input, { key: 'ArrowDown' }); fireEvent.keyDown(input, { key: 'Enter' }); expect(onSearch).toHaveBeenCalledExactlyOnceWith('Blue'); @@ -45,6 +45,43 @@ describe('SearchForm', () => { expect(input).toHaveAttribute('aria-expanded', 'false'); }); + it('filters recent searches client-side while typing a new draft and only intercepts Escape when open', () => { + const onSearch = vi.fn(); + render( + true, + }} + />, + ); + const input = screen.getByRole('combobox', { name: 'Search by album or artist' }); + + // When closed, Escape is not prevented so native input/dialog behavior still works. + expect(fireEvent.keyDown(input, { key: 'Escape' })).toBe(true); + + act(() => input.focus()); + expect(screen.getAllByRole('option')).toHaveLength(2); + + fireEvent.change(input, { target: { value: 'abb' } }); + expect(screen.getAllByRole('option')).toHaveLength(1); + expect(screen.getByRole('option', { name: 'Abbey Road' })).toBeInTheDocument(); + expect(screen.queryByRole('option', { name: 'Blue' })).not.toBeInTheDocument(); + + // When open, Escape closes the popover and prevents default. + expect(fireEvent.keyDown(input, { key: 'Escape' })).toBe(false); + expect(input).toHaveAttribute('aria-expanded', 'false'); + }); + it('does not submit while typing', () => { const onSearch = vi.fn(); render(); diff --git a/client/src/components/SearchForm.tsx b/client/src/components/SearchForm.tsx index 8646dcb..cefcafb 100644 --- a/client/src/components/SearchForm.tsx +++ b/client/src/components/SearchForm.tsx @@ -28,7 +28,13 @@ export default function SearchForm({ query, onSearch, history }: Props) { const input = useRef(null); const area = useRef(null); const historyId = useId(); - const recent = history?.entries.slice(0, 10) ?? []; + const trimmedDraft = draft.trim(); + const filterDraft = + trimmedDraft.length > 0 && trimmedDraft !== query ? trimmedDraft.toLowerCase() : ''; + const allRecent = history?.entries.slice(0, 10) ?? []; + const recent = filterDraft + ? allRecent.filter((entry) => entry.query.toLowerCase().includes(filterDraft)) + : allRecent; const expanded = historyOpen && recent.length > 0; const activeIndex = expanded ? recent.findIndex((entry) => entry.query === activeQuery) @@ -126,6 +132,7 @@ export default function SearchForm({ query, onSearch, history }: Props) { onKeyDownCapture={(event) => { if ( history && + historyOpen && event.key === 'Escape' && !composing && !event.nativeEvent.isComposing @@ -187,7 +194,7 @@ export default function SearchForm({ query, onSearch, history }: Props) { id={historyId} open={historyOpen} activeIndex={activeIndex} - entries={history.entries} + entries={recent} onSelect={select} onClear={() => void clearHistory()} loading={history.loading} diff --git a/client/src/components/ThemeToggle.css b/client/src/components/ThemeToggle.css new file mode 100644 index 0000000..aa1e0cf --- /dev/null +++ b/client/src/components/ThemeToggle.css @@ -0,0 +1,33 @@ +.theme-toggle { + margin-left: auto; + display: inline-flex; + align-items: center; + gap: 0.45rem; + min-height: 2.75rem; + min-width: 2.75rem; + padding: 0.5rem 0.875rem; + border: 1px solid #687d6e; + border-radius: 999px; + background: transparent; + color: var(--header-text); + font-size: 0.875rem; + font-weight: 600; + line-height: 1; + white-space: nowrap; +} +.theme-toggle:hover { + border-color: var(--header-accent); + color: var(--header-accent); +} +.theme-toggle[aria-pressed='true'] { + border-color: var(--header-accent); + background: color-mix(in srgb, var(--header-accent) 16%, transparent); + color: var(--header-accent); +} +.theme-toggle:focus-visible { + outline: 3px solid var(--header-accent); + outline-offset: 4px; +} +.theme-toggle svg { + flex-shrink: 0; +} diff --git a/client/src/components/ThemeToggle.test.tsx b/client/src/components/ThemeToggle.test.tsx new file mode 100644 index 0000000..4980291 --- /dev/null +++ b/client/src/components/ThemeToggle.test.tsx @@ -0,0 +1,78 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import axe from 'axe-core'; + +import { THEME_STORAGE_KEY } from '../hooks/useTheme.js'; +import ThemeToggle from './ThemeToggle.js'; + +function stubColorScheme(dark: boolean) { + vi.stubGlobal( + 'matchMedia', + vi.fn(() => ({ + matches: dark, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + })), + ); +} + +beforeEach(() => { + window.localStorage.clear(); + delete document.documentElement.dataset.theme; + stubColorScheme(false); +}); + +afterEach(() => { + delete document.documentElement.dataset.theme; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +describe('ThemeToggle', () => { + it('defaults to the OS color scheme and toggles and persists the manual override', async () => { + const { container } = render(); + const button = screen.getByRole('button', { name: 'Dark mode', pressed: false }); + expect(document.documentElement.dataset.theme).toBeUndefined(); + + fireEvent.click(button); + expect(button).toHaveAttribute('aria-pressed', 'true'); + expect(document.documentElement.dataset.theme).toBe('dark'); + expect(window.localStorage.getItem(THEME_STORAGE_KEY)).toBe('dark'); + + fireEvent.click(button); + expect(button).toHaveAttribute('aria-pressed', 'false'); + expect(document.documentElement.dataset.theme).toBe('light'); + expect(window.localStorage.getItem(THEME_STORAGE_KEY)).toBe('light'); + + const audit = await axe.run(container, { + rules: { 'color-contrast': { enabled: false } }, + }); + expect(audit.violations.map((v) => v.id)).toEqual([]); + }); + + it('respects OS dark preference when no stored override exists', () => { + stubColorScheme(true); + render(); + const button = screen.getByRole('button', { name: 'Dark mode', pressed: true }); + + fireEvent.click(button); + expect(button).toHaveAttribute('aria-pressed', 'false'); + expect(document.documentElement.dataset.theme).toBe('light'); + expect(window.localStorage.getItem(THEME_STORAGE_KEY)).toBe('light'); + }); + + it('degrades gracefully when localStorage throws', () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { + throw new DOMException('Blocked', 'SecurityError'); + }); + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new DOMException('Quota exceeded', 'QuotaExceededError'); + }); + + render(); + const button = screen.getByRole('button', { name: 'Dark mode', pressed: false }); + fireEvent.click(button); + expect(button).toHaveAttribute('aria-pressed', 'true'); + expect(document.documentElement.dataset.theme).toBe('dark'); + }); +}); diff --git a/client/src/components/ThemeToggle.tsx b/client/src/components/ThemeToggle.tsx new file mode 100644 index 0000000..d41066b --- /dev/null +++ b/client/src/components/ThemeToggle.tsx @@ -0,0 +1,48 @@ +import './ThemeToggle.css'; + +import { useTheme } from '../hooks/useTheme.js'; + +export default function ThemeToggle() { + const { isDark, toggleTheme } = useTheme(); + + return ( + + ); +} diff --git a/client/src/global.css b/client/src/global.css index 31930e3..58c931e 100644 --- a/client/src/global.css +++ b/client/src/global.css @@ -72,10 +72,29 @@ font-synthesis: none; } -/* Follow the system preference; the light theme uses darker green accents - so text and controls retain their contrast on pale surfaces. */ +/* Follow the system preference unless the user picks a manual theme override. + The light theme uses darker green accents so text and controls retain contrast. + Keep in sync with `@media (prefers-color-scheme: dark)` below. */ +:root[data-theme='dark'] { + color-scheme: dark; + --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; +} + +/* Keep in sync with `:root[data-theme='dark']` above. */ @media (prefers-color-scheme: dark) { - :root { + :root:not([data-theme='light']) { color-scheme: dark; --bg: #0a100d; --surface: #111914; @@ -118,9 +137,21 @@ select, input[type='checkbox'] { cursor: pointer; } -button { +button, +.primary-button, +.secondary-button, +.danger-button { border-radius: 6px; padding: 0.65rem 1rem; + min-height: 2.75rem; +} +a.primary-button, +a.secondary-button { + display: inline-flex; + align-items: center; + justify-content: center; + text-decoration: none; + font-weight: 600; } :where(a, button, input, select, textarea, [tabindex]):focus-visible { outline: 3px solid var(--focus); @@ -141,7 +172,7 @@ button { margin: 0 0 0.5rem; text-transform: uppercase; letter-spacing: 0.16em; - font-size: 0.7rem; + font-size: 0.75rem; font-weight: 700; color: var(--accent); } @@ -153,6 +184,15 @@ button { .primary-button:hover { background: var(--accent-hover); } +.danger-button { + background: transparent; + border: 1px solid var(--danger); + color: var(--danger); + font-weight: 600; +} +.danger-button:hover { + background: color-mix(in srgb, var(--danger) 12%, transparent); +} .results h2 { margin: 0; font-size: 1.3rem; diff --git a/client/src/hooks/useTheme.ts b/client/src/hooks/useTheme.ts new file mode 100644 index 0000000..405cf6e --- /dev/null +++ b/client/src/hooks/useTheme.ts @@ -0,0 +1,61 @@ +import { useCallback, useEffect, useState } from 'react'; + +export type Theme = 'light' | 'dark'; + +export const THEME_STORAGE_KEY = 'crate.theme'; + +function readStoredTheme(): Theme | null { + try { + const value = window.localStorage.getItem(THEME_STORAGE_KEY); + return value === 'light' || value === 'dark' ? value : null; + } catch { + return null; + } +} + +function writeStoredTheme(theme: Theme): void { + try { + window.localStorage.setItem(THEME_STORAGE_KEY, theme); + } catch { + // Theme toggle still updates the active document if storage is blocked or full. + } +} + +function getSystemTheme(): Theme { + if (typeof window.matchMedia !== 'function') return 'light'; + return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; +} + +export function useTheme() { + const [override, setOverride] = useState(() => readStoredTheme()); + const [systemTheme, setSystemTheme] = useState(() => getSystemTheme()); + + const theme: Theme = override ?? systemTheme; + + useEffect(() => { + if (override) { + document.documentElement.dataset.theme = override; + } else { + delete document.documentElement.dataset.theme; + } + }, [override]); + + useEffect(() => { + if (typeof window.matchMedia !== 'function') return; + const query = window.matchMedia('(prefers-color-scheme: dark)'); + const handleChange = (event: MediaQueryListEvent) => { + setSystemTheme(event.matches ? 'dark' : 'light'); + }; + query.addEventListener?.('change', handleChange); + return () => query.removeEventListener?.('change', handleChange); + }, []); + + const toggleTheme = useCallback(() => { + const next: Theme = theme === 'dark' ? 'light' : 'dark'; + setOverride(next); + document.documentElement.dataset.theme = next; + writeStoredTheme(next); + }, [theme]); + + return { theme, isDark: theme === 'dark', toggleTheme }; +} diff --git a/client/src/pages/AlbumDetailPage.css b/client/src/pages/AlbumDetailPage.css index 14374c7..0abb7d6 100644 --- a/client/src/pages/AlbumDetailPage.css +++ b/client/src/pages/AlbumDetailPage.css @@ -48,7 +48,9 @@ } .album-detail__artwork-source { /* Visibility reserves the caption's space while the image loads or fails. */ - display: inline-block; + display: inline-flex; + align-items: center; + min-height: 2.75rem; margin-top: 0.75rem; padding-block: 0.5rem; color: var(--muted); @@ -73,6 +75,15 @@ font-size: 1.25rem; margin: 0.75rem 0 0; } +.album-detail__artist-link { + display: inline-flex; + align-items: center; + min-height: 2.75rem; + text-underline-offset: 0.2em; +} +.album-detail__artist-link:hover { + color: var(--accent); +} .album-detail__rating { display: flex; flex-wrap: wrap; @@ -90,13 +101,29 @@ } .album-detail__info .genre-tags { margin: 0 0 1.25rem; + gap: 0.5rem; } .album-detail__info .genre-tags li { + border: 0; + padding: 0; + background: transparent; +} +.album-detail__genre-link { + display: inline-flex; + align-items: center; + min-height: 2.75rem; border: 1px solid var(--border-strong); border-radius: 100px; - padding: 0.25rem 0.625rem; - font-size: 0.75rem; + padding: 0.5rem 0.875rem; + font-size: 0.8125rem; + color: var(--chip-text); background: transparent; + text-decoration: none; +} +.album-detail__genre-link:hover { + border-color: var(--accent); + color: var(--accent); + background: var(--chip-bg); } .album-detail__columns { display: grid; @@ -198,22 +225,41 @@ color: var(--muted); cursor: wait; } +/* Keep in sync with `@media (prefers-color-scheme: light)` below. */ +:root[data-theme='light'] .album-detail .album-detail__artwork { + background: var(--border); + box-shadow: 0 0.5rem 1.5rem color-mix(in srgb, var(--text) 10%, transparent); +} +:root[data-theme='light'] .album-detail .tracklist, +:root[data-theme='light'] .album-detail .review-list article { + background: var(--surface); + border: 1px solid var(--border); + border-radius: 4px; + padding-inline: 0.875rem; +} +:root[data-theme='light'] .album-detail .tracklist li:last-child { + border-bottom: 0; +} +:root[data-theme='light'] .album-detail .review-list { + gap: 0.75rem; +} +/* Keep in sync with `:root[data-theme='light']` above. */ @media (prefers-color-scheme: light) { - .album-detail .album-detail__artwork { + :root:not([data-theme='dark']) .album-detail .album-detail__artwork { background: var(--border); box-shadow: 0 0.5rem 1.5rem color-mix(in srgb, var(--text) 10%, transparent); } - .album-detail .tracklist, - .album-detail .review-list article { + :root:not([data-theme='dark']) .album-detail .tracklist, + :root:not([data-theme='dark']) .album-detail .review-list article { background: var(--surface); border: 1px solid var(--border); border-radius: 4px; padding-inline: 0.875rem; } - .album-detail .tracklist li:last-child { + :root:not([data-theme='dark']) .album-detail .tracklist li:last-child { border-bottom: 0; } - .album-detail .review-list { + :root:not([data-theme='dark']) .album-detail .review-list { gap: 0.75rem; } } diff --git a/client/src/pages/AlbumDetailPage.test.tsx b/client/src/pages/AlbumDetailPage.test.tsx index 9656303..50403ea 100644 --- a/client/src/pages/AlbumDetailPage.test.tsx +++ b/client/src/pages/AlbumDetailPage.test.tsx @@ -61,16 +61,24 @@ it('renders an album tracklist and its first page of reviews', async () => { renderDetail(); const heading = await screen.findByRole('heading', { name: 'Abbey Road' }); + expect(document.title).toBe('Abbey Road — Crate'); const header = heading.closest('header')!; expect(header).toHaveTextContent(/Album.*1969/); - expect(within(header).getByText('The Beatles')).toBeInTheDocument(); - expect(within(header).getByRole('list', { name: 'Genres' })).toHaveTextContent('Rock'); + const artistLink = within(header).getByRole('link', { name: 'The Beatles' }); + expect(artistLink).toHaveAttribute( + 'href', + `${import.meta.env.BASE_URL}?q=The%20Beatles`, + ); + const genreLink = within( + within(header).getByRole('list', { name: 'Genres' }), + ).getByRole('link', { name: 'Rock' }); + expect(genreLink).toHaveAttribute('href', `${import.meta.env.BASE_URL}?genres=1`); expect(header).toHaveTextContent('4.5 out of 5'); expect(within(header).getByText('1 review')).toBeInTheDocument(); - expect(within(header).getByRole('button', { name: 'Add to crate' })).toHaveAttribute( - 'aria-pressed', - 'false', - ); + const crateButton = within(header).getByRole('button', { + name: 'Add to crate: Abbey Road', + }); + expect(crateButton).not.toHaveAttribute('aria-pressed'); expect(header.querySelector('.album-detail__artwork')).toHaveAttribute( 'aria-hidden', 'true', @@ -131,7 +139,7 @@ it('shows shared detail artwork and an accessible source link, retaining the fal expect( screen.queryByRole('link', { name: 'Artwork via Cover Art Archive' }), ).not.toBeInTheDocument(); - expect(screen.getByRole('button', { name: 'Add to crate' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'Add to crate: Abbey Road' })).toBeEnabled(); const audit = await axe.run(container, { rules: { 'color-contrast': { enabled: false } }, }); @@ -158,7 +166,9 @@ it('omits missing secondary metadata and shows an unrated album without broken a expect(header).toHaveTextContent('Not yet rated'); expect(header).toHaveTextContent('0 reviews'); expect(header.querySelector('img')).not.toBeInTheDocument(); - expect(within(header).getByRole('button', { name: 'Add to crate' })).toBeEnabled(); + expect( + within(header).getByRole('button', { name: 'Add to crate: Untitled album' }), + ).toBeEnabled(); }); it('keeps very long titles and multiple artist names in full', async () => { @@ -174,7 +184,8 @@ it('keeps very long titles and multiple artist names in full', async () => { expect( await screen.findByRole('heading', { level: 1, name: title }), ).toBeInTheDocument(); - expect(screen.getByText(artist + ', Guest artist')).toBeInTheDocument(); + expect(screen.getByRole('link', { name: artist })).toBeInTheDocument(); + expect(screen.getByRole('link', { name: 'Guest artist' })).toBeInTheDocument(); }); it('shows API track numbers in returned order with full titles and formatted durations', async () => { @@ -265,6 +276,7 @@ it('shows a useful error state when an album cannot be loaded', async () => { ); expect(await screen.findByRole('alert')).toHaveTextContent('could not load this album'); + expect(document.title).toBe('Album unavailable — Crate'); expect(screen.getByRole('link', { name: '← Back to Discover' })).toHaveAttribute( 'href', `${import.meta.env.BASE_URL}?q=Abbey&sort=TITLE_ASC`, @@ -358,7 +370,7 @@ it('shows the community heading and a useful empty state', async () => { expect(within(reviews).getByText(/No reviews yet/)).toHaveTextContent( 'Be the first to share what you think.', ); - expect(within(reviews).getByRole('group', { name: 'Rating' })).toBeInTheDocument(); + expect(within(reviews).getByRole('radiogroup', { name: 'Rating' })).toBeInTheDocument(); }); it('keeps long authors and comments in full with an accessible rating and date', async () => { @@ -437,7 +449,9 @@ it('keeps loaded reviews and offers retry after a pagination error', async () => ); const more = await screen.findByRole('button', { name: 'Load more reviews' }); fireEvent.click(more); - expect(await screen.findByRole('alert')).toHaveTextContent('Offline'); + expect(await screen.findByRole('alert')).toHaveTextContent( + 'Could not load more reviews. Please try again.', + ); expect(screen.getByText('A classic.')).toBeInTheDocument(); expect(more).toHaveAttribute('aria-disabled', 'false'); fireEvent.click(more); diff --git a/client/src/pages/AlbumDetailPage.tsx b/client/src/pages/AlbumDetailPage.tsx index 7a7605f..630c23d 100644 --- a/client/src/pages/AlbumDetailPage.tsx +++ b/client/src/pages/AlbumDetailPage.tsx @@ -1,7 +1,7 @@ import '../components/AlbumCard.css'; import './AlbumDetailPage.css'; -import { useEffect, useRef, useState } from 'react'; +import { Fragment, useEffect, useRef, useState } from 'react'; import { useQuery } from '@apollo/client/react'; import { ALBUM_DETAIL } from '../api/albumDetail.js'; @@ -35,6 +35,16 @@ export default function AlbumDetailPage({ id }: { id: string }) { }); const discoveryHref = appHref('/', location.search); + useEffect(() => { + if (loading && !data) { + document.title = 'Loading album — Crate'; + } else if (error || !data?.album) { + document.title = 'Album unavailable — Crate'; + } else { + document.title = `${data.album.title || 'Untitled album'} — Crate`; + } + }, [loading, error, data]); + useEffect(() => { if ( !loadingMoreReviews && @@ -78,11 +88,9 @@ export default function AlbumDetailPage({ id }: { id: string }) { if (result.data?.album?.reviews.pageInfo.hasNextPage !== false) { reviewButtonHadFocus.current = false; } - } catch (caught) { + } catch { reviewButtonHadFocus.current = false; - setReviewsError( - caught instanceof Error ? caught.message : 'Could not load more reviews.', - ); + setReviewsError('Could not load more reviews. Please try again.'); } finally { setLoadingMoreReviews(false); } @@ -109,11 +117,9 @@ export default function AlbumDetailPage({ id }: { id: string }) { } const { album } = data; + const displayTitle = album.title || 'Untitled album'; const reviews = album.reviews.edges.map((edge) => edge.node); - const artists = album.artists - .map((artist) => artist.name) - .filter(Boolean) - .join(', '); + const namedArtists = album.artists.filter((artist) => Boolean(artist.name)); const rating = album.reviewCount > 0 ? album.averageRating : null; return ( @@ -152,8 +158,22 @@ export default function AlbumDetailPage({ id }: { id: string }) {

Album{album.releaseYear !== null && <> · {album.releaseYear}}

-

{album.title || 'Untitled album'}

- {artists &&

{artists}

} +

{displayTitle}

+ {namedArtists.length > 0 && ( +

+ {namedArtists.map((artist, index) => ( + + {index > 0 && ', '} + + {artist.name} + + + ))} +

+ )}

{rating === null ? ( Not yet rated @@ -170,11 +190,22 @@ export default function AlbumDetailPage({ id }: { id: string }) { {album.genres.length > 0 && (

    {album.genres.map((genre) => ( -
  • {genre.name}
  • +
  • + + {genre.name} + +
  • ))}
)} - +
@@ -274,7 +305,11 @@ export default function AlbumDetailPage({ id }: { id: string }) { Load more reviews )} - {reviewsError &&

{reviewsError}

} + {reviewsError && ( +

+ {reviewsError} +

+ )} diff --git a/client/src/pages/CratePage.css b/client/src/pages/CratePage.css index 534a60e..117f813 100644 --- a/client/src/pages/CratePage.css +++ b/client/src/pages/CratePage.css @@ -10,7 +10,7 @@ margin: 0.25rem 0 1rem; } -.crate-page > .album-grid { +.crate-page .album-grid { margin-top: 1.5rem; } diff --git a/client/src/pages/CratePage.test.tsx b/client/src/pages/CratePage.test.tsx index 6b4beb8..722c6b4 100644 --- a/client/src/pages/CratePage.test.tsx +++ b/client/src/pages/CratePage.test.tsx @@ -62,13 +62,14 @@ describe('CratePage', () => { expect( await screen.findByRole('heading', { name: 'Abbey Road' }), ).toBeInTheDocument(); + expect(document.title).toBe('Your crate — Crate'); expect(screen.getByText('Showing 1 of 1 albums in your crate.')).toBeInTheDocument(); expect( - screen.getByRole('button', { name: /remove from crate/i }), + screen.getByRole('button', { name: 'Remove from crate: Abbey Road' }), ).toBeInTheDocument(); }); - it('removes an album and updates the list', async () => { + it('removes an album, updates the list, and restores keyboard focus', async () => { render( { ); await screen.findByRole('heading', { name: 'Abbey Road' }); - fireEvent.click(screen.getByRole('button', { name: /remove from crate/i })); + const removeButton = screen.getByRole('button', { + name: 'Remove from crate: Abbey Road', + }); + removeButton.focus(); + fireEvent.click(removeButton); // The list, the count and the empty state all have to follow the removal. expect(await screen.findByText('Nothing saved yet')).toBeInTheDocument(); expect(screen.queryByRole('heading', { name: 'Abbey Road' })).not.toBeInTheDocument(); - expect(screen.getByText('Your crate is empty.')).toBeInTheDocument(); + const status = screen.getByText('Your crate is empty.'); + expect(status).toBeInTheDocument(); + await waitFor(() => expect(status).toHaveFocus()); }); - it('appends the next page when Load more succeeds', async () => { + it('appends the next page when Load more succeeds and restores focus on the last page', async () => { const second = { ...item, id: '11', @@ -134,10 +141,14 @@ describe('CratePage', () => { ); await screen.findByRole('heading', { name: 'Abbey Road' }); - fireEvent.click(screen.getByRole('button', { name: 'Load more' })); + const loadMore = screen.getByRole('button', { name: 'Load more' }); + loadMore.focus(); + fireEvent.click(loadMore); expect(await screen.findByRole('heading', { name: 'Let It Be' })).toBeInTheDocument(); - expect(screen.getByText('Showing 2 of 2 albums in your crate.')).toBeInTheDocument(); + const status = screen.getByText('Showing 2 of 2 albums in your crate.'); + expect(status).toBeInTheDocument(); + await waitFor(() => expect(status).toHaveFocus()); }); it('keeps the loaded albums and retries when loading more fails', async () => { diff --git a/client/src/pages/CratePage.tsx b/client/src/pages/CratePage.tsx index f997bcb..467f744 100644 --- a/client/src/pages/CratePage.tsx +++ b/client/src/pages/CratePage.tsx @@ -1,6 +1,6 @@ import './CratePage.css'; -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { useQuery } from '@apollo/client/react'; import { MY_CRATE } from '../api/crate.js'; @@ -15,6 +15,10 @@ export default function CratePage() { const [loadingMore, setLoadingMore] = useState(false); const [pageError, setPageError] = useState(false); const [retrying, setRetrying] = useState(false); + const statusRef = useRef(null); + const listRef = useRef(null); + const loadMoreHadFocus = useRef(false); + const removedIndexRef = useRef(null); const { data, loading, error, fetchMore, refetch } = useQuery(MY_CRATE, { variables: { first: PAGE_SIZE, after: null }, }); @@ -22,15 +26,55 @@ export default function CratePage() { const crate = data?.myCrate; const albums = crate?.edges.map((edge) => edge.node.album) ?? []; - async function loadMore() { + useEffect(() => { + document.title = error ? 'Could not load your crate — Crate' : 'Your crate — Crate'; + }, [error]); + + useEffect(() => { + if ( + !loadingMore && + crate?.pageInfo.hasNextPage === false && + loadMoreHadFocus.current + ) { + loadMoreHadFocus.current = false; + // The final page removes Load more; restore focus only if it fell to body. + if (document.activeElement === document.body) { + statusRef.current?.focus({ preventScroll: true }); + } + } + }, [loadingMore, crate?.pageInfo.hasNextPage]); + + useEffect(() => { + if (removedIndexRef.current === null || loading) return; + const removedIndex = removedIndexRef.current; + removedIndexRef.current = null; + + if (document.activeElement !== document.body) return; + + const links = + listRef.current?.querySelectorAll('.album-card__link'); + if (links && links.length > 0) { + const target = links[Math.min(removedIndex, links.length - 1)]; + target?.focus({ preventScroll: true }); + } else { + statusRef.current?.focus({ preventScroll: true }); + } + }, [albums.length, loading]); + + async function loadMore(button: HTMLButtonElement) { const after = crate?.pageInfo.endCursor; - if (!after) return; + if (!after || loadingMore) return; + loadMoreHadFocus.current = document.activeElement === button; setLoadingMore(true); setPageError(false); try { - await fetchMore({ variables: { first: PAGE_SIZE, after } }); + const result = await fetchMore({ variables: { first: PAGE_SIZE, after } }); + if (result.data?.myCrate.pageInfo.hasNextPage !== false) { + loadMoreHadFocus.current = false; + } } catch { + loadMoreHadFocus.current = false; // Keep the albums that did load; the same button is the retry, so no // state is lost and the cursor is unchanged. setPageError(true); @@ -60,7 +104,13 @@ export default function CratePage() {

Saved for later

Your crate

-

+

{loading && !crate ? 'Loading your crate…' : loadingMore @@ -107,10 +157,15 @@ export default function CratePage() { {/* An h2 here: the album cards start at h3, and jumping from the page's h1 to an h3 is a heading-order violation. */}

Saved albums

-
    - {albums.map((album) => ( +
      + {albums.map((album, index) => (
    • - + { + removedIndexRef.current = index; + }} + />
    • ))}
    @@ -125,8 +180,8 @@ export default function CratePage() {