From c290667b8a70ea03ade71416ecc4750d4010b824 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 27 Nov 2026 03:21:55 -0500 Subject: [PATCH] refactor(web): genre and year albums page like every other list (DRY W6) The genre and year drill-downs hand-rolled their own pager (a request token to drop late answers, loading, failed and later-page-failed flags), on the note that the codebase had no way to make a query from a changing URL. The search pages have since done exactly that: $derived(q ? createXInfiniteQuery(q) : null). browse.ts gains createAlbumsByGenreInfiniteQuery and createAlbumsByYearInfiniteQuery, keyed per selection so a late page for the previous one never lands in the current list. Both pages draw their albums through one AlbumDrillDown view (back link, count, grid, ListContinuation), and the out-of-date note is gone. Tests drive the pages through mockInfiniteQuery, as the search pages' do, with the page() fixture now in test-utils. Co-Authored-By: Claude Opus 5.5 --- web/src/lib/api/browse.ts | 37 ++++-- web/src/lib/api/queries.ts | 2 + web/src/lib/components/AlbumDrillDown.svelte | 87 +++++++++++++ web/src/routes/library/genres/+page.svelte | 128 +++---------------- web/src/routes/library/genres/genres.test.ts | 87 +++++++------ web/src/routes/library/years/+page.svelte | 123 ++---------------- web/src/routes/library/years/years.test.ts | 95 ++++++++------ web/src/test-utils/fixtures/page.ts | 6 + 8 files changed, 257 insertions(+), 308 deletions(-) create mode 100644 web/src/lib/components/AlbumDrillDown.svelte create mode 100644 web/src/test-utils/fixtures/page.ts diff --git a/web/src/lib/api/browse.ts b/web/src/lib/api/browse.ts index b4e0fb00..8243e6ba 100644 --- a/web/src/lib/api/browse.ts +++ b/web/src/lib/api/browse.ts @@ -1,6 +1,7 @@ -import { createQuery } from '@tanstack/svelte-query'; +import { createInfiniteQuery, createQuery } from '@tanstack/svelte-query'; import { api } from './client'; import { qk } from './queries'; +import { pageGetNextPageParam } from './paging'; import type { AlbumRef, Page } from './types'; export const BROWSE_PAGE_SIZE = 50; @@ -22,10 +23,8 @@ export async function listAlbumYears(): Promise { return api.get('/api/library/years'); } -// The indexes use svelte-query: they're fetched once per page mount, so static -// options are enough, and the cache means bouncing between browse and a -// drill-down doesn't refetch. The drill-down lists below deliberately do NOT — -// see the note on listAlbumsByGenre. +// The indexes are cached, so bouncing between browse and a drill-down doesn't +// refetch them. export function createGenresQuery() { return createQuery({ queryKey: qk.genres(), @@ -47,11 +46,6 @@ export function createAlbumYearsQuery() { // contain slashes ("Rock/Pop" is a real tag), which a path segment cannot // carry — the server would see two segments, and a hard reload of such a URL // would not survive the SPA fallback either. -// -// Called directly rather than through createInfiniteQuery because the selected -// genre comes from the URL and changes without remounting the page. This -// codebase has no reactive-query-options pattern, and introducing one here -// would be a larger change than the feature warrants. export async function listAlbumsByGenre( genre: string, limit: number, @@ -80,3 +74,26 @@ export async function listAlbumsByYear( }); return api.get>(`/api/library/albums?${params}`); } + +// The drill-down lists, a page at a time. The selection comes from the URL and +// changes without remounting the page, so a page creates its query from the +// selection: `$derived(genre ? createAlbumsByGenreInfiniteQuery(genre) : null)`. +// Each selection has its own cache key, so a late page for the previous one +// never lands in the current list. +export function createAlbumsByGenreInfiniteQuery(genre: string) { + return createInfiniteQuery({ + queryKey: qk.albumsByGenre(genre), + queryFn: ({ pageParam = 0 }) => listAlbumsByGenre(genre, BROWSE_PAGE_SIZE, pageParam), + initialPageParam: 0, + getNextPageParam: pageGetNextPageParam() + }); +} + +export function createAlbumsByYearInfiniteQuery(year: number) { + return createInfiniteQuery({ + queryKey: qk.albumsByYear(year), + queryFn: ({ pageParam = 0 }) => listAlbumsByYear(year, BROWSE_PAGE_SIZE, pageParam), + initialPageParam: 0, + getNextPageParam: pageGetNextPageParam() + }); +} diff --git a/web/src/lib/api/queries.ts b/web/src/lib/api/queries.ts index 4270b315..3d8eb366 100644 --- a/web/src/lib/api/queries.ts +++ b/web/src/lib/api/queries.ts @@ -74,6 +74,8 @@ export const qk = { // svelte-query because their selection comes from the URL. genres: () => ['genres'] as const, albumYears: () => ['albumYears'] as const, + albumsByGenre: (genre: string) => ['albumsByGenre', genre] as const, + albumsByYear: (year: number) => ['albumsByYear', year] as const, }; export function createArtistsQuery(sort: ArtistSort) { diff --git a/web/src/lib/components/AlbumDrillDown.svelte b/web/src/lib/components/AlbumDrillDown.svelte new file mode 100644 index 00000000..01fc205a --- /dev/null +++ b/web/src/lib/components/AlbumDrillDown.svelte @@ -0,0 +1,87 @@ + + +
+
+ + +
+

{title}

+ {#if query && !query.isPending && !failed} +

{plural(total, 'album', 'albums')}

+ {/if} +
+
+ + {#if failed} +

+ {failText} + +

+ {:else if !query || query.isPending} +

Loading…

+ {:else if albums.length === 0} + + {:else} +
+ {#each albums as album (album.id)} + + {/each} +
+ query?.fetchNextPage()} + {endLabel} + /> + {/if} +
diff --git a/web/src/routes/library/genres/+page.svelte b/web/src/routes/library/genres/+page.svelte index ba7b0e18..9eeda96a 100644 --- a/web/src/routes/library/genres/+page.svelte +++ b/web/src/routes/library/genres/+page.svelte @@ -2,19 +2,15 @@ import { plural } from '#lib/utils/plural.js'; import { page } from '$app/state'; import { pageTitle } from '#lib/branding.js'; - import { ChevronLeft } from 'lucide-svelte'; import { createGenresQuery, - listAlbumsByGenre, - BROWSE_PAGE_SIZE, + createAlbumsByGenreInfiniteQuery, type GenreCount } from '#lib/api/browse.js'; - import AlbumCard from '#lib/components/AlbumCard.svelte'; + import AlbumDrillDown from '#lib/components/AlbumDrillDown.svelte'; import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte'; import EmptyState from '#lib/components/EmptyState.svelte'; - import ListContinuation from '#lib/components/ListContinuation.svelte'; import QuickFilter from '#lib/components/QuickFilter.svelte'; - import type { AlbumRef } from '#lib/api/types.js'; const indexStore = createGenresQuery(); const index = $derived($indexStore); @@ -57,57 +53,8 @@ return list; // server order: count DESC, then name }); - let albums = $state([]); - let total = $state(0); - let loading = $state(false); - let failed = $state(false); - // A later page failed: the albums already shown stay, and the list offers a - // retry at its end instead of loading again on every scroll. - let moreFailed = $state(false); - - // Plain `let`, deliberately not $state: it's read inside the fetch path, and - // as reactive state that read would make this effect depend on its own - // writes. Its only job is to let a late response for a previous genre be - // discarded rather than painted over the current one. - let requestToken = 0; - - $effect(() => { - const g = selected; // the only tracked read — reload when selection moves - void reload(g); - }); - - async function reload(genre: string) { - requestToken += 1; - albums = []; - total = 0; - failed = false; - moreFailed = false; - if (!genre) return; - await fetchPage(genre, 0, requestToken); - } - - async function fetchPage(genre: string, offset: number, token: number) { - loading = true; - try { - const p = await listAlbumsByGenre(genre, BROWSE_PAGE_SIZE, offset); - if (token !== requestToken) return; // selection moved on; drop it - albums = offset === 0 ? p.items : [...albums, ...p.items]; - total = p.total; - } catch { - if (token === requestToken) { - if (offset === 0) failed = true; - else moreFailed = true; - } - } finally { - if (token === requestToken) loading = false; - } - } - - function loadMore() { - if (loading) return; - moreFailed = false; - void fetchPage(selected, albums.length, requestToken); - } + const albumsStore = $derived(selected ? createAlbumsByGenreInfiniteQuery(selected) : null); + const albums = $derived(albumsStore ? $albumsStore : null); function genreHref(genre: string): string { return `/library/genres?g=${encodeURIComponent(genre)}`; @@ -119,61 +66,18 @@ {#if selected} -
-
- - -
-

{selected}

- {#if !loading || albums.length > 0} -

- {plural(total, 'album', 'albums')} -

- {/if} -
-
- - {#if failed} -

- Couldn't load albums for this genre. - -

- {:else if loading && albums.length === 0} -

Loading…

- {:else if albums.length === 0} - - - {:else} -
- {#each albums as album (album.id)} - - {/each} -
- - {/if} -
+ + {:else}
diff --git a/web/src/routes/library/genres/genres.test.ts b/web/src/routes/library/genres/genres.test.ts index 8798275a..489fcc4c 100644 --- a/web/src/routes/library/genres/genres.test.ts +++ b/web/src/routes/library/genres/genres.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { render, screen, waitFor, fireEvent } from '@testing-library/svelte'; -import { mockQuery } from '#test-utils/query.js'; +import { mockInfiniteQuery, mockQuery } from '#test-utils/query.js'; +import { page } from '#test-utils/fixtures/page.js'; import { installIntersectionObserverMock } from '#test-utils/intersectionObserver.js'; import { pageUrlModule } from '#test-utils/mocks/appState.js'; import { apiClientMock } from '#test-utils/mocks/client.js'; @@ -16,7 +17,7 @@ vi.mock('$app/state', () => pageUrlModule(pageState)); vi.mock('#lib/api/browse.js', () => ({ BROWSE_PAGE_SIZE: 2, createGenresQuery: vi.fn(), - listAlbumsByGenre: vi.fn() + createAlbumsByGenreInfiniteQuery: vi.fn() })); vi.mock('#lib/api/client.js', () => apiClientMock()); @@ -30,7 +31,7 @@ vi.mock('#lib/player/store.svelte.js', () => ({ })); import GenresPage from './+page.svelte'; -import { createGenresQuery, listAlbumsByGenre } from '#lib/api/browse.js'; +import { createGenresQuery, createAlbumsByGenreInfiniteQuery } from '#lib/api/browse.js'; const asMock = (fn: unknown) => fn as ReturnType; @@ -176,57 +177,67 @@ describe('/library/genres index', () => { }); describe('/library/genres drill-down', () => { - test('fetches and renders albums for the selected genre', async () => { + test('fetches and renders albums for the selected genre', () => { pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock%2FPop'); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByGenre).mockResolvedValue({ - items: [album('a1', 'First Album')], - total: 1, - limit: 2, - offset: 0 - }); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ pages: [page([album('a1', 'First Album')], 1)] }) + ); render(GenresPage); // The decoded genre must reach the API, not the percent-encoded form. - await waitFor(() => expect(listAlbumsByGenre).toHaveBeenCalledWith('Rock/Pop', 2, 0)); - expect(await screen.findByText('First Album')).toBeInTheDocument(); + expect(createAlbumsByGenreInfiniteQuery).toHaveBeenCalledWith('Rock/Pop'); + expect(screen.getByText('First Album')).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Rock/Pop' })).toBeInTheDocument(); }); - test('scrolling to the end loads the next page, then reports the end', async () => { + test('scrolling to the end loads the next page', async () => { pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByGenre) - .mockResolvedValueOnce({ - items: [album('a1', 'One'), album('a2', 'Two')], - total: 3, - limit: 2, - offset: 0 + const fetchNextPage = vi.fn(); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)], + hasNextPage: true, + fetchNextPage }) - .mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); + ); render(GenresPage); - await screen.findByText('One'); // No button: reaching the bottom of the grid loads the next page. expect(screen.queryByRole('button', { name: /load more/i })).not.toBeInTheDocument(); await waitFor(() => { io.scrollToEnd(); - expect(listAlbumsByGenre).toHaveBeenLastCalledWith('Rock', 2, 2); + expect(fetchNextPage).toHaveBeenCalled(); }); + }); - expect(await screen.findByText('Three')).toBeInTheDocument(); - // Earlier pages are appended, not replaced. + test('the last page says the list has ended', () => { + pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); + asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3), page([album('a3', 'Three')], 3, 2)] + }) + ); + render(GenresPage); + + // Pages are appended, not replaced. expect(screen.getByText('One')).toBeInTheDocument(); - expect(await screen.findByText('End of genre')).toBeInTheDocument(); + expect(screen.getByText('Three')).toBeInTheDocument(); + expect(screen.getByText('End of genre')).toBeInTheDocument(); }); test('a failed drill-down offers a retry rather than an empty grid', async () => { pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByGenre).mockRejectedValue(new Error('nope')); + const refetch = vi.fn(); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue(mockInfiniteQuery({ isError: true, refetch })); render(GenresPage); - expect(await screen.findByText(/Couldn't load albums for this genre/i)).toBeInTheDocument(); + expect(screen.getByText(/Couldn't load albums for this genre/i)).toBeInTheDocument(); + await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); + expect(refetch).toHaveBeenCalled(); }); // A failed later page keeps what is shown and offers a retry at the end, @@ -234,21 +245,23 @@ describe('/library/genres drill-down', () => { test('a failed later page keeps the albums and offers Try again', async () => { pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByGenre) - .mockResolvedValueOnce({ items: [album('a1', 'One'), album('a2', 'Two')], total: 3, limit: 2, offset: 0 }) - .mockRejectedValueOnce(new Error('nope')) - .mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); + const fetchNextPage = vi.fn(); + asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)], + isError: true, + hasNextPage: true, + isFetchNextPageError: true, + fetchNextPage + }) + ); render(GenresPage); - await screen.findByText('One'); - await waitFor(() => { - io.scrollToEnd(); - expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more."); - }); + expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more."); expect(screen.getByText('One')).toBeInTheDocument(); expect(screen.queryByText(/Couldn't load albums for this genre/i)).not.toBeInTheDocument(); await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); - expect(await screen.findByText('Three')).toBeInTheDocument(); + expect(fetchNextPage).toHaveBeenCalled(); }); }); diff --git a/web/src/routes/library/years/+page.svelte b/web/src/routes/library/years/+page.svelte index 39853951..80b527d0 100644 --- a/web/src/routes/library/years/+page.svelte +++ b/web/src/routes/library/years/+page.svelte @@ -2,18 +2,14 @@ import { plural } from '#lib/utils/plural.js'; import { page } from '$app/state'; import { pageTitle } from '#lib/branding.js'; - import { ChevronLeft } from 'lucide-svelte'; import { createAlbumYearsQuery, - listAlbumsByYear, - BROWSE_PAGE_SIZE, + createAlbumsByYearInfiniteQuery, type YearCount } from '#lib/api/browse.js'; - import AlbumCard from '#lib/components/AlbumCard.svelte'; + import AlbumDrillDown from '#lib/components/AlbumDrillDown.svelte'; import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte'; import EmptyState from '#lib/components/EmptyState.svelte'; - import ListContinuation from '#lib/components/ListContinuation.svelte'; - import type { AlbumRef } from '#lib/api/types.js'; const indexStore = createAlbumYearsQuery(); const index = $derived($indexStore); @@ -46,57 +42,8 @@ })); }); - let albums = $state([]); - let total = $state(0); - let loading = $state(false); - let failed = $state(false); - // A later page failed: the albums already shown stay, and the list offers a - // retry at its end instead of loading again on every scroll. - let moreFailed = $state(false); - - // Plain `let`, not $state — see the note in the genres page: as reactive - // state, reading it in the fetch path would make the effect below depend on - // its own writes. It exists so a late response for a previously selected - // year is discarded instead of painted over the current one. - let requestToken = 0; - - $effect(() => { - const y = selected; // only tracked read - void reload(y); - }); - - async function reload(year: number | null) { - requestToken += 1; - albums = []; - total = 0; - failed = false; - moreFailed = false; - if (year === null) return; - await fetchPage(year, 0, requestToken); - } - - async function fetchPage(year: number, offset: number, token: number) { - loading = true; - try { - const p = await listAlbumsByYear(year, BROWSE_PAGE_SIZE, offset); - if (token !== requestToken) return; - albums = offset === 0 ? p.items : [...albums, ...p.items]; - total = p.total; - } catch { - if (token === requestToken) { - if (offset === 0) failed = true; - else moreFailed = true; - } - } finally { - if (token === requestToken) loading = false; - } - } - - function loadMore() { - if (selected === null || loading) return; - moreFailed = false; - void fetchPage(selected, albums.length, requestToken); - } + const albumsStore = $derived(selected !== null ? createAlbumsByYearInfiniteQuery(selected) : null); + const albums = $derived(albumsStore ? $albumsStore : null); @@ -104,58 +51,16 @@ {#if selected !== null} -
-
- - -
-

{selected}

- {#if !loading || albums.length > 0} -

- {plural(total, 'album', 'albums')} -

- {/if} -
-
- - {#if failed} -

- Couldn't load albums for {selected}. - -

- {:else if loading && albums.length === 0} -

Loading…

- {:else if albums.length === 0} - - {:else} -
- {#each albums as album (album.id)} - - {/each} -
- - {/if} -
+ {:else}
diff --git a/web/src/routes/library/years/years.test.ts b/web/src/routes/library/years/years.test.ts index ac833f84..698d754b 100644 --- a/web/src/routes/library/years/years.test.ts +++ b/web/src/routes/library/years/years.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { render, screen, waitFor, fireEvent } from '@testing-library/svelte'; -import { mockQuery } from '#test-utils/query.js'; +import { mockInfiniteQuery, mockQuery } from '#test-utils/query.js'; +import { page } from '#test-utils/fixtures/page.js'; import { installIntersectionObserverMock } from '#test-utils/intersectionObserver.js'; import { pageUrlModule } from '#test-utils/mocks/appState.js'; import { apiClientMock } from '#test-utils/mocks/client.js'; @@ -16,7 +17,7 @@ vi.mock('$app/state', () => pageUrlModule(pageState)); vi.mock('#lib/api/browse.js', () => ({ BROWSE_PAGE_SIZE: 2, createAlbumYearsQuery: vi.fn(), - listAlbumsByYear: vi.fn() + createAlbumsByYearInfiniteQuery: vi.fn() })); vi.mock('#lib/api/client.js', () => apiClientMock()); @@ -30,7 +31,7 @@ vi.mock('#lib/player/store.svelte.js', () => ({ })); import YearsPage from './+page.svelte'; -import { createAlbumYearsQuery, listAlbumsByYear } from '#lib/api/browse.js'; +import { createAlbumYearsQuery, createAlbumsByYearInfiniteQuery } from '#lib/api/browse.js'; const asMock = (fn: unknown) => fn as ReturnType; @@ -125,19 +126,17 @@ describe('/library/years index', () => { }); describe('/library/years drill-down', () => { - test('requests the selected year as a degenerate range', async () => { + test('requests the selected year and renders its albums', () => { pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByYear).mockResolvedValue({ - items: [album('a1', 'Mid Nineties')], - total: 1, - limit: 2, - offset: 0 - }); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ pages: [page([album('a1', 'Mid Nineties')], 1)] }) + ); render(YearsPage); - await waitFor(() => expect(listAlbumsByYear).toHaveBeenCalledWith(1995, 2, 0)); - expect(await screen.findByText('Mid Nineties')).toBeInTheDocument(); + expect(createAlbumsByYearInfiniteQuery).toHaveBeenCalledWith(1995); + expect(screen.getByText('Mid Nineties')).toBeInTheDocument(); + expect(screen.getByText('1 album')).toBeInTheDocument(); }); test('a non-numeric year is treated as no selection', () => { @@ -148,43 +147,57 @@ describe('/library/years drill-down', () => { render(YearsPage); // Falls back to the index rather than fetching NaN. - expect(listAlbumsByYear).not.toHaveBeenCalled(); + expect(createAlbumsByYearInfiniteQuery).not.toHaveBeenCalled(); expect(screen.getByRole('heading', { level: 1, name: 'Years' })).toBeInTheDocument(); }); - test('scrolling to the end loads the next page, then reports the end', async () => { + test('scrolling to the end loads the next page', async () => { pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByYear) - .mockResolvedValueOnce({ - items: [album('a1', 'One'), album('a2', 'Two')], - total: 3, - limit: 2, - offset: 0 + const fetchNextPage = vi.fn(); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)], + hasNextPage: true, + fetchNextPage }) - .mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); + ); render(YearsPage); - await screen.findByText('One'); // No button: reaching the bottom of the grid loads the next page. expect(screen.queryByRole('button', { name: /load more/i })).not.toBeInTheDocument(); await waitFor(() => { io.scrollToEnd(); - expect(listAlbumsByYear).toHaveBeenLastCalledWith(1995, 2, 2); + expect(fetchNextPage).toHaveBeenCalled(); }); - - expect(await screen.findByText('Three')).toBeInTheDocument(); - expect(screen.getByText('One')).toBeInTheDocument(); - expect(await screen.findByText('End of year')).toBeInTheDocument(); }); - test('a failed drill-down offers a retry', async () => { + test('the last page says the list has ended', () => { pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByYear).mockRejectedValue(new Error('nope')); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3), page([album('a3', 'Three')], 3, 2)] + }) + ); render(YearsPage); - expect(await screen.findByText(/Couldn't load albums for 1995/i)).toBeInTheDocument(); + // Pages are appended, not replaced. + expect(screen.getByText('One')).toBeInTheDocument(); + expect(screen.getByText('Three')).toBeInTheDocument(); + expect(screen.getByText('End of year')).toBeInTheDocument(); + }); + + test('a failed drill-down offers a retry rather than an empty grid', async () => { + pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); + asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); + const refetch = vi.fn(); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue(mockInfiniteQuery({ isError: true, refetch })); + render(YearsPage); + + expect(screen.getByText(/Couldn't load albums for 1995/i)).toBeInTheDocument(); + await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); + expect(refetch).toHaveBeenCalled(); }); // A failed later page keeps what is shown and offers a retry at the end, @@ -192,21 +205,23 @@ describe('/library/years drill-down', () => { test('a failed later page keeps the albums and offers Try again', async () => { pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); - asMock(listAlbumsByYear) - .mockResolvedValueOnce({ items: [album('a1', 'One'), album('a2', 'Two')], total: 3, limit: 2, offset: 0 }) - .mockRejectedValueOnce(new Error('nope')) - .mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); + const fetchNextPage = vi.fn(); + asMock(createAlbumsByYearInfiniteQuery).mockReturnValue( + mockInfiniteQuery({ + pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)], + isError: true, + hasNextPage: true, + isFetchNextPageError: true, + fetchNextPage + }) + ); render(YearsPage); - await screen.findByText('One'); - await waitFor(() => { - io.scrollToEnd(); - expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more."); - }); + expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more."); expect(screen.getByText('One')).toBeInTheDocument(); expect(screen.queryByText(/Couldn't load albums for 1995/i)).not.toBeInTheDocument(); await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); - expect(await screen.findByText('Three')).toBeInTheDocument(); + expect(fetchNextPage).toHaveBeenCalled(); }); }); diff --git a/web/src/test-utils/fixtures/page.ts b/web/src/test-utils/fixtures/page.ts new file mode 100644 index 00000000..fdc8207c --- /dev/null +++ b/web/src/test-utils/fixtures/page.ts @@ -0,0 +1,6 @@ +import type { Page } from '#lib/api/types.js'; + +/** A Page envelope, as the server sends a paged list. */ +export function page(items: T[], total: number, offset = 0, limit = 50): Page { + return { items, total, offset, limit }; +}