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:
2026-11-27 03:21:55 -05:00
co-authored by Claude Opus 5.5
parent 7314101f91
commit c290667b8a
8 changed files with 257 additions and 308 deletions
+27 -10
View File
@@ -1,6 +1,7 @@
import { createQuery } from '@tanstack/svelte-query'; import { createInfiniteQuery, createQuery } from '@tanstack/svelte-query';
import { api } from './client'; import { api } from './client';
import { qk } from './queries'; import { qk } from './queries';
import { pageGetNextPageParam } from './paging';
import type { AlbumRef, Page } from './types'; import type { AlbumRef, Page } from './types';
export const BROWSE_PAGE_SIZE = 50; export const BROWSE_PAGE_SIZE = 50;
@@ -22,10 +23,8 @@ export async function listAlbumYears(): Promise<YearCount[]> {
return api.get<YearCount[]>('/api/library/years'); return api.get<YearCount[]>('/api/library/years');
} }
// The indexes use svelte-query: they're fetched once per page mount, so static // The indexes are cached, so bouncing between browse and a drill-down doesn't
// options are enough, and the cache means bouncing between browse and a // refetch them.
// drill-down doesn't refetch. The drill-down lists below deliberately do NOT —
// see the note on listAlbumsByGenre.
export function createGenresQuery() { export function createGenresQuery() {
return createQuery({ return createQuery({
queryKey: qk.genres(), queryKey: qk.genres(),
@@ -47,11 +46,6 @@ export function createAlbumYearsQuery() {
// contain slashes ("Rock/Pop" is a real tag), which a path segment cannot // 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 // carry — the server would see two segments, and a hard reload of such a URL
// would not survive the SPA fallback either. // 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( export async function listAlbumsByGenre(
genre: string, genre: string,
limit: number, limit: number,
@@ -80,3 +74,26 @@ export async function listAlbumsByYear(
}); });
return api.get<Page<AlbumRef>>(`/api/library/albums?${params}`); return api.get<Page<AlbumRef>>(`/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<AlbumRef>()
});
}
export function createAlbumsByYearInfiniteQuery(year: number) {
return createInfiniteQuery({
queryKey: qk.albumsByYear(year),
queryFn: ({ pageParam = 0 }) => listAlbumsByYear(year, BROWSE_PAGE_SIZE, pageParam),
initialPageParam: 0,
getNextPageParam: pageGetNextPageParam<AlbumRef>()
});
}
+2
View File
@@ -74,6 +74,8 @@ export const qk = {
// svelte-query because their selection comes from the URL. // svelte-query because their selection comes from the URL.
genres: () => ['genres'] as const, genres: () => ['genres'] as const,
albumYears: () => ['albumYears'] 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) { export function createArtistsQuery(sort: ArtistSort) {
@@ -0,0 +1,87 @@
<script lang="ts">
import { ChevronLeft } from 'lucide-svelte';
import { plural } from '#lib/utils/plural.js';
import AlbumCard from './AlbumCard.svelte';
import EmptyState from './EmptyState.svelte';
import ListContinuation from './ListContinuation.svelte';
import type { AlbumRef, Page } from '#lib/api/types.js';
// One browse axis's albums (a genre, a year): a back link to the axis, the
// count, and the paged grid. A failed first page offers Try again; a failed
// later page keeps the grid and offers it at the end.
type AlbumPages = {
data?: { pages: Page<AlbumRef>[] };
isPending: boolean;
isError: boolean;
hasNextPage: boolean;
isFetchingNextPage: boolean;
isFetchNextPageError: boolean;
fetchNextPage: () => unknown;
refetch: () => unknown;
};
let {
query,
backHref,
backLabel,
title,
failText,
emptyTitle,
emptyHint,
endLabel
}: {
query: AlbumPages | null;
backHref: string;
backLabel: string;
title: string;
failText: string;
emptyTitle: string;
emptyHint: string;
endLabel: string;
} = $props();
const albums = $derived(query?.data?.pages.flatMap((p) => p.items) ?? []);
const total = $derived(query?.data?.pages[0]?.total ?? 0);
const failed = $derived(!!query?.isError && albums.length === 0);
</script>
<div class="space-y-4">
<header class="space-y-2">
<a href={backHref} class="inline-flex items-center gap-1 text-sm text-accent-fg hover:underline">
<ChevronLeft size={14} aria-hidden="true" />
{backLabel}
</a>
<div>
<h1 class="font-display text-2xl font-medium text-text-primary">{title}</h1>
{#if query && !query.isPending && !failed}
<p class="text-sm text-text-secondary">{plural(total, 'album', 'albums')}</p>
{/if}
</div>
</header>
{#if failed}
<p class="text-sm text-action-destructive">
{failText}
<button type="button" class="underline hover:no-underline" onclick={() => query?.refetch()}
>Try again</button
>
</p>
{:else if !query || query.isPending}
<p class="text-text-secondary">Loading…</p>
{:else if albums.length === 0}
<EmptyState title={emptyTitle} hint={emptyHint} />
{: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={query.hasNextPage}
loading={query.isFetchingNextPage}
failed={query.isFetchNextPageError}
onMore={() => query?.fetchNextPage()}
{endLabel}
/>
{/if}
</div>
+16 -112
View File
@@ -2,19 +2,15 @@
import { plural } from '#lib/utils/plural.js'; import { plural } from '#lib/utils/plural.js';
import { page } from '$app/state'; import { page } from '$app/state';
import { pageTitle } from '#lib/branding.js'; import { pageTitle } from '#lib/branding.js';
import { ChevronLeft } from 'lucide-svelte';
import { import {
createGenresQuery, createGenresQuery,
listAlbumsByGenre, createAlbumsByGenreInfiniteQuery,
BROWSE_PAGE_SIZE,
type GenreCount type GenreCount
} from '#lib/api/browse.js'; } 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 ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte';
import EmptyState from '#lib/components/EmptyState.svelte'; import EmptyState from '#lib/components/EmptyState.svelte';
import ListContinuation from '#lib/components/ListContinuation.svelte';
import QuickFilter from '#lib/components/QuickFilter.svelte'; import QuickFilter from '#lib/components/QuickFilter.svelte';
import type { AlbumRef } from '#lib/api/types.js';
const indexStore = createGenresQuery(); const indexStore = createGenresQuery();
const index = $derived($indexStore); const index = $derived($indexStore);
@@ -57,57 +53,8 @@
return list; // server order: count DESC, then name return list; // server order: count DESC, then name
}); });
let albums = $state<AlbumRef[]>([]); const albumsStore = $derived(selected ? createAlbumsByGenreInfiniteQuery(selected) : null);
let total = $state(0); const albums = $derived(albumsStore ? $albumsStore : null);
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);
}
function genreHref(genre: string): string { function genreHref(genre: string): string {
return `/library/genres?g=${encodeURIComponent(genre)}`; return `/library/genres?g=${encodeURIComponent(genre)}`;
@@ -119,61 +66,18 @@
</svelte:head> </svelte:head>
{#if selected} {#if selected}
<div class="space-y-4"> <!-- An empty list is reachable when a genre in the index has since been
<header class="space-y-2"> rescanned away. -->
<a <AlbumDrillDown
href="/library/genres" query={albums}
class="inline-flex items-center gap-1 text-sm text-accent-fg hover:underline" backHref="/library/genres"
> backLabel="All genres"
<ChevronLeft size={14} aria-hidden="true" /> title={selected}
All genres failText="Couldn't load albums for this genre."
</a> emptyTitle="No albums for this genre"
<div> emptyHint="The library may have been rescanned since this list was built."
<h1 class="font-display text-2xl font-medium text-text-primary">{selected}</h1> endLabel="End of genre"
{#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>
{:else} {:else}
<div class="space-y-4"> <div class="space-y-4">
<header class="flex flex-wrap items-end justify-between gap-3"> <header class="flex flex-wrap items-end justify-between gap-3">
+50 -37
View File
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/svelte'; 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 { installIntersectionObserverMock } from '#test-utils/intersectionObserver.js';
import { pageUrlModule } from '#test-utils/mocks/appState.js'; import { pageUrlModule } from '#test-utils/mocks/appState.js';
import { apiClientMock } from '#test-utils/mocks/client.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', () => ({ vi.mock('#lib/api/browse.js', () => ({
BROWSE_PAGE_SIZE: 2, BROWSE_PAGE_SIZE: 2,
createGenresQuery: vi.fn(), createGenresQuery: vi.fn(),
listAlbumsByGenre: vi.fn() createAlbumsByGenreInfiniteQuery: vi.fn()
})); }));
vi.mock('#lib/api/client.js', () => apiClientMock()); vi.mock('#lib/api/client.js', () => apiClientMock());
@@ -30,7 +31,7 @@ vi.mock('#lib/player/store.svelte.js', () => ({
})); }));
import GenresPage from './+page.svelte'; 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>; const asMock = (fn: unknown) => fn as ReturnType<typeof vi.fn>;
@@ -176,57 +177,67 @@ describe('/library/genres index', () => {
}); });
describe('/library/genres drill-down', () => { 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'); pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock%2FPop');
asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] }));
asMock(listAlbumsByGenre).mockResolvedValue({ asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue(
items: [album('a1', 'First Album')], mockInfiniteQuery({ pages: [page([album('a1', 'First Album')], 1)] })
total: 1, );
limit: 2,
offset: 0
});
render(GenresPage); render(GenresPage);
// The decoded genre must reach the API, not the percent-encoded form. // The decoded genre must reach the API, not the percent-encoded form.
await waitFor(() => expect(listAlbumsByGenre).toHaveBeenCalledWith('Rock/Pop', 2, 0)); expect(createAlbumsByGenreInfiniteQuery).toHaveBeenCalledWith('Rock/Pop');
expect(await screen.findByText('First Album')).toBeInTheDocument(); expect(screen.getByText('First Album')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Rock/Pop' })).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'); pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock');
asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] }));
asMock(listAlbumsByGenre) const fetchNextPage = vi.fn();
.mockResolvedValueOnce({ asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue(
items: [album('a1', 'One'), album('a2', 'Two')], mockInfiniteQuery({
total: 3, pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)],
limit: 2, hasNextPage: true,
offset: 0 fetchNextPage
}) })
.mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); );
render(GenresPage); render(GenresPage);
await screen.findByText('One');
// No button: reaching the bottom of the grid loads the next page. // No button: reaching the bottom of the grid loads the next page.
expect(screen.queryByRole('button', { name: /load more/i })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: /load more/i })).not.toBeInTheDocument();
await waitFor(() => { await waitFor(() => {
io.scrollToEnd(); io.scrollToEnd();
expect(listAlbumsByGenre).toHaveBeenLastCalledWith('Rock', 2, 2); expect(fetchNextPage).toHaveBeenCalled();
}); });
});
expect(await screen.findByText('Three')).toBeInTheDocument(); test('the last page says the list has ended', () => {
// Earlier pages are appended, not replaced. 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(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 () => { test('a failed drill-down offers a retry rather than an empty grid', async () => {
pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock');
asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] }));
asMock(listAlbumsByGenre).mockRejectedValue(new Error('nope')); const refetch = vi.fn();
asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue(mockInfiniteQuery({ isError: true, refetch }));
render(GenresPage); 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, // 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 () => { test('a failed later page keeps the albums and offers Try again', async () => {
pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock'); pageState.pageUrl = new URL('http://localhost/library/genres?g=Rock');
asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] })); asMock(createGenresQuery).mockReturnValue(mockQuery({ data: [] }));
asMock(listAlbumsByGenre) const fetchNextPage = vi.fn();
.mockResolvedValueOnce({ items: [album('a1', 'One'), album('a2', 'Two')], total: 3, limit: 2, offset: 0 }) asMock(createAlbumsByGenreInfiniteQuery).mockReturnValue(
.mockRejectedValueOnce(new Error('nope')) mockInfiniteQuery({
.mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)],
isError: true,
hasNextPage: true,
isFetchNextPageError: true,
fetchNextPage
})
);
render(GenresPage); render(GenresPage);
await screen.findByText('One'); expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more.");
await waitFor(() => {
io.scrollToEnd();
expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more.");
});
expect(screen.getByText('One')).toBeInTheDocument(); expect(screen.getByText('One')).toBeInTheDocument();
expect(screen.queryByText(/Couldn't load albums for this genre/i)).not.toBeInTheDocument(); expect(screen.queryByText(/Couldn't load albums for this genre/i)).not.toBeInTheDocument();
await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); await fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
expect(await screen.findByText('Three')).toBeInTheDocument(); expect(fetchNextPage).toHaveBeenCalled();
}); });
}); });
+14 -109
View File
@@ -2,18 +2,14 @@
import { plural } from '#lib/utils/plural.js'; import { plural } from '#lib/utils/plural.js';
import { page } from '$app/state'; import { page } from '$app/state';
import { pageTitle } from '#lib/branding.js'; import { pageTitle } from '#lib/branding.js';
import { ChevronLeft } from 'lucide-svelte';
import { import {
createAlbumYearsQuery, createAlbumYearsQuery,
listAlbumsByYear, createAlbumsByYearInfiniteQuery,
BROWSE_PAGE_SIZE,
type YearCount type YearCount
} from '#lib/api/browse.js'; } 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 ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte';
import EmptyState from '#lib/components/EmptyState.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 indexStore = createAlbumYearsQuery();
const index = $derived($indexStore); const index = $derived($indexStore);
@@ -46,57 +42,8 @@
})); }));
}); });
let albums = $state<AlbumRef[]>([]); const albumsStore = $derived(selected !== null ? createAlbumsByYearInfiniteQuery(selected) : null);
let total = $state(0); const albums = $derived(albumsStore ? $albumsStore : null);
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);
}
</script> </script>
<svelte:head> <svelte:head>
@@ -104,58 +51,16 @@
</svelte:head> </svelte:head>
{#if selected !== null} {#if selected !== null}
<div class="space-y-4"> <AlbumDrillDown
<header class="space-y-2"> query={albums}
<a backHref="/library/years"
href="/library/years" backLabel="All years"
class="inline-flex items-center gap-1 text-sm text-accent-fg hover:underline" title={String(selected)}
> failText={`Couldn't load albums for ${selected}.`}
<ChevronLeft size={14} aria-hidden="true" /> emptyTitle={`No albums from ${selected}`}
All years emptyHint="The library may have been rescanned since this list was built."
</a> endLabel="End of year"
<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>
{:else} {:else}
<div class="space-y-4"> <div class="space-y-4">
<header> <header>
+55 -40
View File
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/svelte'; 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 { installIntersectionObserverMock } from '#test-utils/intersectionObserver.js';
import { pageUrlModule } from '#test-utils/mocks/appState.js'; import { pageUrlModule } from '#test-utils/mocks/appState.js';
import { apiClientMock } from '#test-utils/mocks/client.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', () => ({ vi.mock('#lib/api/browse.js', () => ({
BROWSE_PAGE_SIZE: 2, BROWSE_PAGE_SIZE: 2,
createAlbumYearsQuery: vi.fn(), createAlbumYearsQuery: vi.fn(),
listAlbumsByYear: vi.fn() createAlbumsByYearInfiniteQuery: vi.fn()
})); }));
vi.mock('#lib/api/client.js', () => apiClientMock()); vi.mock('#lib/api/client.js', () => apiClientMock());
@@ -30,7 +31,7 @@ vi.mock('#lib/player/store.svelte.js', () => ({
})); }));
import YearsPage from './+page.svelte'; 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>; const asMock = (fn: unknown) => fn as ReturnType<typeof vi.fn>;
@@ -125,19 +126,17 @@ describe('/library/years index', () => {
}); });
describe('/library/years drill-down', () => { 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'); pageState.pageUrl = new URL('http://localhost/library/years?y=1995');
asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] }));
asMock(listAlbumsByYear).mockResolvedValue({ asMock(createAlbumsByYearInfiniteQuery).mockReturnValue(
items: [album('a1', 'Mid Nineties')], mockInfiniteQuery({ pages: [page([album('a1', 'Mid Nineties')], 1)] })
total: 1, );
limit: 2,
offset: 0
});
render(YearsPage); render(YearsPage);
await waitFor(() => expect(listAlbumsByYear).toHaveBeenCalledWith(1995, 2, 0)); expect(createAlbumsByYearInfiniteQuery).toHaveBeenCalledWith(1995);
expect(await screen.findByText('Mid Nineties')).toBeInTheDocument(); expect(screen.getByText('Mid Nineties')).toBeInTheDocument();
expect(screen.getByText('1 album')).toBeInTheDocument();
}); });
test('a non-numeric year is treated as no selection', () => { test('a non-numeric year is treated as no selection', () => {
@@ -148,43 +147,57 @@ describe('/library/years drill-down', () => {
render(YearsPage); render(YearsPage);
// Falls back to the index rather than fetching NaN. // 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(); 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'); pageState.pageUrl = new URL('http://localhost/library/years?y=1995');
asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] }));
asMock(listAlbumsByYear) const fetchNextPage = vi.fn();
.mockResolvedValueOnce({ asMock(createAlbumsByYearInfiniteQuery).mockReturnValue(
items: [album('a1', 'One'), album('a2', 'Two')], mockInfiniteQuery({
total: 3, pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)],
limit: 2, hasNextPage: true,
offset: 0 fetchNextPage
}) })
.mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); );
render(YearsPage); render(YearsPage);
await screen.findByText('One');
// No button: reaching the bottom of the grid loads the next page. // No button: reaching the bottom of the grid loads the next page.
expect(screen.queryByRole('button', { name: /load more/i })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: /load more/i })).not.toBeInTheDocument();
await waitFor(() => { await waitFor(() => {
io.scrollToEnd(); 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'); pageState.pageUrl = new URL('http://localhost/library/years?y=1995');
asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); 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); 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, // 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 () => { test('a failed later page keeps the albums and offers Try again', async () => {
pageState.pageUrl = new URL('http://localhost/library/years?y=1995'); pageState.pageUrl = new URL('http://localhost/library/years?y=1995');
asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] })); asMock(createAlbumYearsQuery).mockReturnValue(mockQuery({ data: [] }));
asMock(listAlbumsByYear) const fetchNextPage = vi.fn();
.mockResolvedValueOnce({ items: [album('a1', 'One'), album('a2', 'Two')], total: 3, limit: 2, offset: 0 }) asMock(createAlbumsByYearInfiniteQuery).mockReturnValue(
.mockRejectedValueOnce(new Error('nope')) mockInfiniteQuery({
.mockResolvedValueOnce({ items: [album('a3', 'Three')], total: 3, limit: 2, offset: 2 }); pages: [page([album('a1', 'One'), album('a2', 'Two')], 3)],
isError: true,
hasNextPage: true,
isFetchNextPageError: true,
fetchNextPage
})
);
render(YearsPage); render(YearsPage);
await screen.findByText('One'); expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more.");
await waitFor(() => {
io.scrollToEnd();
expect(screen.getByRole('alert')).toHaveTextContent("Couldn't load more.");
});
expect(screen.getByText('One')).toBeInTheDocument(); expect(screen.getByText('One')).toBeInTheDocument();
expect(screen.queryByText(/Couldn't load albums for 1995/i)).not.toBeInTheDocument(); expect(screen.queryByText(/Couldn't load albums for 1995/i)).not.toBeInTheDocument();
await fireEvent.click(screen.getByRole('button', { name: 'Try again' })); await fireEvent.click(screen.getByRole('button', { name: 'Try again' }));
expect(await screen.findByText('Three')).toBeInTheDocument(); expect(fetchNextPage).toHaveBeenCalled();
}); });
}); });
+6
View File
@@ -0,0 +1,6 @@
import type { Page } from '#lib/api/types.js';
/** A Page<T> envelope, as the server sends a paged list. */
export function page<T>(items: T[], total: number, offset = 0, limit = 50): Page<T> {
return { items, total, offset, limit };
}