fix: paginate the bookmarks and collections lists with Load more

Both lists fetched a single capped page (100 / 200) with no pager, so entries
past the cap were silently unreachable. Add a reusable LoadMore component that
seeds from the streamed first page (preserving the auth gate + inline error
handling) and fetches further offset-based pages on demand, and wire it into
the bookmarks and collections pages.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-07-11 15:12:03 +02:00
parent c308eb3eac
commit 3ca05dcb58
8 changed files with 293 additions and 11 deletions

View File

@@ -0,0 +1,73 @@
import { test, expect, type Page } from './fixtures';
// The bookmarks list pages the results: the first 50 load with the page, and a
// "Load more" button fetches the next page (offset-based) and appends it, so
// bookmarks past the first page are reachable rather than silently truncated.
function bookmark(i: number) {
return {
id: `bm-${i}`,
manga_id: `m-${i}`,
manga_title: `Manga ${i}`,
manga_cover_image_path: null,
chapter_id: null,
chapter_number: null,
page: null,
created_at: '2026-01-01T00:00:00Z'
};
}
async function authed(page: Page) {
await page.route('**/api/v1/auth/config', (r) =>
r.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ self_register_enabled: true, private_mode: false })
})
);
await page.route('**/api/v1/auth/me', (r) =>
r.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
user: { id: 'u1', username: 'reader', created_at: '2026-01-01T00:00:00Z', is_admin: false }
})
})
);
await page.route('**/api/v1/auth/me/preferences', (r) =>
r.fulfill({ status: 200, contentType: 'application/json', body: '{}' })
);
await page.route('**/api/v1/files/**', (r) => r.fulfill({ status: 200, body: '' }));
}
test('bookmarks list loads more pages on demand', async ({ page }) => {
await authed(page);
// total = 60: first page 50 (offset 0), second page 10 (offset 50).
await page.route('**/api/v1/me/bookmarks*', (r) => {
const url = new URL(r.request().url());
const offset = Number(url.searchParams.get('offset') ?? '0');
const items =
offset === 0
? Array.from({ length: 50 }, (_, i) => bookmark(i))
: Array.from({ length: 10 }, (_, i) => bookmark(50 + i));
return r.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ items, page: { limit: 50, offset, total: 60 } })
});
});
await page.goto('/bookmarks');
// First page rendered; more remain so the button shows.
await expect(page.getByText('Manga 0')).toBeVisible();
await expect(page.getByText('Manga 49')).toBeVisible();
await expect(page.getByText('Manga 50')).toHaveCount(0);
const loadMore = page.getByTestId('load-more');
await expect(loadMore).toBeVisible();
// Load the rest; the button disappears once everything is shown.
await loadMore.click();
await expect(page.getByText('Manga 59')).toBeVisible();
await expect(loadMore).toHaveCount(0);
});

View File

@@ -0,0 +1,74 @@
import { test, expect, type Page } from './fixtures';
// The collections grid pages results: a "Load more" button fetches the next
// page (offset-based) and appends it, so collections past the first page are
// reachable rather than silently truncated at the old 200 cap.
function collection(i: number) {
return {
id: `col-${i}`,
user_id: 'u1',
name: `Collection ${i}`,
description: null,
created_at: '2026-01-01T00:00:00Z',
updated_at: '2026-01-01T00:00:00Z',
manga_count: 0,
sample_covers: []
};
}
async function authed(page: Page) {
await page.route('**/api/v1/auth/config', (r) =>
r.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ self_register_enabled: true, private_mode: false })
})
);
await page.route('**/api/v1/auth/me', (r) =>
r.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
user: { id: 'u1', username: 'reader', created_at: '2026-01-01T00:00:00Z', is_admin: false }
})
})
);
await page.route('**/api/v1/auth/me/preferences', (r) =>
r.fulfill({ status: 200, contentType: 'application/json', body: '{}' })
);
await page.route('**/api/v1/me/bookmarks*', (r) =>
r.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ items: [], page: { limit: 50, offset: 0, total: 0 } })
})
);
}
test('collections grid loads more pages on demand', async ({ page }) => {
await authed(page);
await page.route('**/api/v1/me/collections*', (r) => {
const offset = Number(new URL(r.request().url()).searchParams.get('offset') ?? '0');
const items =
offset === 0
? Array.from({ length: 60 }, (_, i) => collection(i))
: Array.from({ length: 5 }, (_, i) => collection(60 + i));
return r.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ items, page: { limit: 60, offset, total: 65 } })
});
});
await page.goto('/collections');
await expect(page.getByText('Collection 0')).toBeVisible();
await expect(page.getByText('Collection 64')).toHaveCount(0);
const loadMore = page.getByTestId('load-more');
await expect(loadMore).toBeVisible();
await loadMore.click();
await expect(page.getByText('Collection 64')).toBeVisible();
await expect(loadMore).toHaveCount(0);
});

View File

@@ -1,6 +1,6 @@
{
"name": "mangalord-frontend",
"version": "0.127.1",
"version": "0.127.2",
"private": true,
"type": "module",
"scripts": {

View File

@@ -0,0 +1,83 @@
<script lang="ts" generics="T">
import { ApiError } from '$lib/api/client';
// Renders an accumulating list with a "Load more" button. The parent seeds
// the first page (`initial` + `total`, usually from a streamed loader that
// also gates auth); further pages are fetched on demand via `fetchMore`,
// which is handed the current item count as its offset. The `children`
// snippet receives the accumulated array so the parent controls layout.
let {
initial,
total,
fetchMore,
children
}: {
initial: T[];
total: number | null;
fetchMore: (offset: number) => Promise<{ items: T[]; total: number | null }>;
children: import('svelte').Snippet<[T[]]>;
} = $props();
let extra = $state<T[]>([]);
let curTotal = $state<number | null>(total);
let loading = $state(false);
let error = $state<string | null>(null);
const all = $derived([...initial, ...extra]);
const hasMore = $derived(curTotal != null && all.length < curTotal);
async function more() {
loading = true;
error = null;
try {
const r = await fetchMore(all.length);
extra = [...extra, ...r.items];
curTotal = r.total;
} catch (e) {
error = e instanceof ApiError ? e.message : 'Could not load more.';
} finally {
loading = false;
}
}
</script>
{@render children(all)}
{#if hasMore}
<div class="load-more">
<button type="button" onclick={more} disabled={loading} data-testid="load-more">
{loading ? 'Loading…' : 'Load more'}
</button>
{#if error}
<p class="lm-error" role="alert">{error}</p>
{/if}
</div>
{/if}
<style>
.load-more {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-2);
margin-top: var(--space-3);
}
button {
padding: var(--space-2) var(--space-4);
border: 1px solid var(--border);
border-radius: var(--radius-md, 8px);
background: transparent;
color: inherit;
font: inherit;
cursor: pointer;
}
button:disabled {
opacity: 0.6;
cursor: default;
}
.lm-error {
color: var(--danger, #dc2626);
font-size: var(--font-sm);
margin: 0;
}
</style>

View File

@@ -1,8 +1,15 @@
<script lang="ts">
import BookmarkList from '$lib/components/BookmarkList.svelte';
import ListRowSkeleton from '$lib/components/ListRowSkeleton.svelte';
import LoadMore from '$lib/components/LoadMore.svelte';
import { listMyBookmarks, type Bookmark } from '$lib/api/bookmarks';
let { data } = $props();
async function fetchMore(offset: number) {
const p = await listMyBookmarks({ limit: data.pageSize, offset });
return { items: p.items, total: p.page.total };
}
</script>
<h1>Bookmarks</h1>
@@ -21,7 +28,11 @@
{:else if r.bookmarks.length === 0}
<p class="hint" data-testid="bookmarks-empty">No bookmarks yet.</p>
{:else}
<BookmarkList bookmarks={r.bookmarks} />
<LoadMore initial={r.bookmarks as Bookmark[]} total={r.total} {fetchMore}>
{#snippet children(items: Bookmark[])}
<BookmarkList bookmarks={items} />
{/snippet}
</LoadMore>
{/if}
{/await}

View File

@@ -4,17 +4,32 @@ import type { PageLoad } from './$types';
export const ssr = false;
/** First-page size; "Load more" pulls further pages of the same size.
* Not exported — SvelteKit only allows specific `+page.ts` exports. */
const BOOKMARKS_PAGE_SIZE = 50;
export const load: PageLoad = async () => {
// Streamed (the load itself doesn't await) so the list shows a skeleton
// while the single fetch — which is also the auth gate — is in flight.
return {
pageSize: BOOKMARKS_PAGE_SIZE,
result: (async () => {
try {
const page = await listMyBookmarks();
return { bookmarks: page.items, authenticated: true, error: null as string | null };
const page = await listMyBookmarks({ limit: BOOKMARKS_PAGE_SIZE, offset: 0 });
return {
bookmarks: page.items,
total: page.page.total,
authenticated: true,
error: null as string | null
};
} catch (e) {
if (e instanceof ApiError && e.status === 401) {
return { bookmarks: [], authenticated: false, error: null as string | null };
return {
bookmarks: [],
total: 0,
authenticated: false,
error: null as string | null
};
}
// Anything else — an HTTP error (502 upstream_unavailable from
// a backend restart, 500 internal_error) or a raw network
@@ -23,7 +38,7 @@ export const load: PageLoad = async () => {
// right UX for a transient API blip and the user is already
// authenticated as far as we know.
const message = e instanceof ApiError ? e.message : 'Something went wrong.';
return { bookmarks: [], authenticated: true, error: message };
return { bookmarks: [], total: 0, authenticated: true, error: message };
}
})()
};

View File

@@ -1,8 +1,15 @@
<script lang="ts">
import CollectionsGrid from '$lib/components/CollectionsGrid.svelte';
import MangaGridSkeleton from '$lib/components/MangaGridSkeleton.svelte';
import LoadMore from '$lib/components/LoadMore.svelte';
import { listMyCollections, type CollectionSummary } from '$lib/api/collections';
let { data } = $props();
async function fetchMore(offset: number) {
const p = await listMyCollections({ limit: data.pageSize, offset });
return { items: p.items, total: p.page.total };
}
</script>
<h1>Collections</h1>
@@ -22,7 +29,11 @@
<strong>Add to collection</strong> to start one.
</p>
{:else}
<CollectionsGrid collections={r.collections} />
<LoadMore initial={r.collections as CollectionSummary[]} total={r.total} {fetchMore}>
{#snippet children(items: CollectionSummary[])}
<CollectionsGrid collections={items} />
{/snippet}
</LoadMore>
{/if}
{/await}

View File

@@ -4,23 +4,38 @@ import type { PageLoad } from './$types';
export const ssr = false;
/** First-page size; "Load more" pulls further pages of the same size.
* Not exported — SvelteKit only allows specific `+page.ts` exports. */
const COLLECTIONS_PAGE_SIZE = 60;
export const load: PageLoad = async () => {
// Streamed so the grid shows a skeleton while the single fetch (also the
// auth gate) is in flight.
return {
pageSize: COLLECTIONS_PAGE_SIZE,
result: (async () => {
try {
const page = await listMyCollections({ limit: 200 });
return { collections: page.items, authenticated: true, error: null as string | null };
const page = await listMyCollections({ limit: COLLECTIONS_PAGE_SIZE, offset: 0 });
return {
collections: page.items,
total: page.page.total,
authenticated: true,
error: null as string | null
};
} catch (e) {
if (e instanceof ApiError && e.status === 401) {
return { collections: [], authenticated: false, error: null as string | null };
return {
collections: [],
total: 0,
authenticated: false,
error: null as string | null
};
}
// An HTTP error or a raw network failure (a non-ApiError
// TypeError) renders inline rather than escaping to the
// framework error page for a transient API blip.
const message = e instanceof ApiError ? e.message : 'Something went wrong.';
return { collections: [], authenticated: true, error: message };
return { collections: [], total: 0, authenticated: true, error: message };
}
})()
};