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 <noreply@anthropic.com>
This commit is contained in:
@@ -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<AlbumRef[]>([]);
|
||||
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 @@
|
||||
</svelte:head>
|
||||
|
||||
{#if selected}
|
||||
<div class="space-y-4">
|
||||
<header class="space-y-2">
|
||||
<a
|
||||
href="/library/genres"
|
||||
class="inline-flex items-center gap-1 text-sm text-accent-fg hover:underline"
|
||||
>
|
||||
<ChevronLeft size={14} aria-hidden="true" />
|
||||
All genres
|
||||
</a>
|
||||
<div>
|
||||
<h1 class="font-display text-2xl font-medium text-text-primary">{selected}</h1>
|
||||
{#if !loading || albums.length > 0}
|
||||
<p class="text-sm text-text-secondary">
|
||||
{plural(total, 'album', 'albums')}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{#if failed}
|
||||
<p class="text-sm text-action-destructive">
|
||||
Couldn't load albums for this genre.
|
||||
<button
|
||||
type="button"
|
||||
class="underline hover:no-underline"
|
||||
onclick={() => reload(selected)}>Try again</button
|
||||
>
|
||||
</p>
|
||||
{:else if loading && albums.length === 0}
|
||||
<p class="text-text-secondary">Loading…</p>
|
||||
{:else if albums.length === 0}
|
||||
<!-- Reachable when a genre exists in the index but its albums have since
|
||||
been rescanned away. Not the multi-genre bug that made this whole
|
||||
surface worth care — the server splits on both sides now. -->
|
||||
<EmptyState
|
||||
title="No albums for this genre"
|
||||
hint="The library may have been rescanned since this list was built."
|
||||
/>
|
||||
{:else}
|
||||
<div
|
||||
class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6"
|
||||
>
|
||||
{#each albums as album (album.id)}
|
||||
<AlbumCard {album} />
|
||||
{/each}
|
||||
</div>
|
||||
<ListContinuation
|
||||
hasMore={albums.length < total}
|
||||
{loading}
|
||||
failed={moreFailed}
|
||||
onMore={loadMore}
|
||||
endLabel="End of genre"
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
<!-- An empty list is reachable when a genre in the index has since been
|
||||
rescanned away. -->
|
||||
<AlbumDrillDown
|
||||
query={albums}
|
||||
backHref="/library/genres"
|
||||
backLabel="All genres"
|
||||
title={selected}
|
||||
failText="Couldn't load albums for this genre."
|
||||
emptyTitle="No albums for this genre"
|
||||
emptyHint="The library may have been rescanned since this list was built."
|
||||
endLabel="End of genre"
|
||||
/>
|
||||
{:else}
|
||||
<div class="space-y-4">
|
||||
<header class="flex flex-wrap items-end justify-between gap-3">
|
||||
|
||||
@@ -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<typeof vi.fn>;
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<AlbumRef[]>([]);
|
||||
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);
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
@@ -104,58 +51,16 @@
|
||||
</svelte:head>
|
||||
|
||||
{#if selected !== null}
|
||||
<div class="space-y-4">
|
||||
<header class="space-y-2">
|
||||
<a
|
||||
href="/library/years"
|
||||
class="inline-flex items-center gap-1 text-sm text-accent-fg hover:underline"
|
||||
>
|
||||
<ChevronLeft size={14} aria-hidden="true" />
|
||||
All years
|
||||
</a>
|
||||
<div>
|
||||
<h1 class="font-display text-2xl font-medium text-text-primary">{selected}</h1>
|
||||
{#if !loading || albums.length > 0}
|
||||
<p class="text-sm text-text-secondary">
|
||||
{plural(total, 'album', 'albums')}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{#if failed}
|
||||
<p class="text-sm text-action-destructive">
|
||||
Couldn't load albums for {selected}.
|
||||
<button
|
||||
type="button"
|
||||
class="underline hover:no-underline"
|
||||
onclick={() => reload(selected)}>Try again</button
|
||||
>
|
||||
</p>
|
||||
{:else if loading && albums.length === 0}
|
||||
<p class="text-text-secondary">Loading…</p>
|
||||
{:else if albums.length === 0}
|
||||
<EmptyState
|
||||
title="No albums from {selected}"
|
||||
hint="The library may have been rescanned since this list was built."
|
||||
/>
|
||||
{:else}
|
||||
<div
|
||||
class="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6"
|
||||
>
|
||||
{#each albums as album (album.id)}
|
||||
<AlbumCard {album} />
|
||||
{/each}
|
||||
</div>
|
||||
<ListContinuation
|
||||
hasMore={albums.length < total}
|
||||
{loading}
|
||||
failed={moreFailed}
|
||||
onMore={loadMore}
|
||||
endLabel="End of year"
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
<AlbumDrillDown
|
||||
query={albums}
|
||||
backHref="/library/years"
|
||||
backLabel="All years"
|
||||
title={String(selected)}
|
||||
failText={`Couldn't load albums for ${selected}.`}
|
||||
emptyTitle={`No albums from ${selected}`}
|
||||
emptyHint="The library may have been rescanned since this list was built."
|
||||
endLabel="End of year"
|
||||
/>
|
||||
{:else}
|
||||
<div class="space-y-4">
|
||||
<header>
|
||||
|
||||
@@ -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<typeof vi.fn>;
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user