feat: bookmarks (CRUD + per-user listing + frontend toggle)
Backend:
- Migration 0004_bookmarks_unique.sql adds a partial unique index on
(user_id, manga_id) WHERE chapter_id IS NULL. The 0001 UNIQUE
constraint over (user_id, manga_id, chapter_id) doesn't block dupes
when chapter_id is NULL under Postgres's default NULLS DISTINCT, so a
user could otherwise bookmark the same manga twice at the manga
level. Chapter-level dupes are still caught by the 0001 constraint.
- repo::bookmark with create / list_for_user / find_owner / delete.
create catches the 23505 unique violation and surfaces it as
AppError::Conflict so handlers return a clean 409.
- POST /api/v1/bookmarks { manga_id, chapter_id?, page? } — CurrentUser
required. Pre-validates the manga exists (404 if not) and, when
chapter_id is supplied, that the chapter belongs to that manga (also
404), so FK violations can't bubble up as 500s.
- DELETE /api/v1/bookmarks/{id} — owner-only. 404 if unknown, 403 if it
exists for another user, 204 on success. Idempotent: deleting an
already-deleted bookmark is 404, not 500.
- GET /api/v1/me/bookmarks — paged envelope, sorted by created_at DESC,
scoped to the current user so the URL itself can't be used to peek at
someone else's bookmarks.
Integration coverage in tests/api_bookmarks.rs (9 cases): create+list
returns only own; duplicate manga-level bookmark → 409; unknown manga
→ 404; unauthenticated POST → 401; user A cannot delete user B's
bookmark (403); unknown delete → 404; double-delete → 404, not 500;
/me/bookmarks requires auth; paged envelope shape on empty list.
Frontend:
- lib/api/bookmarks.ts with createBookmark / deleteBookmark /
listMyBookmarks. listMyBookmarksOrEmpty wraps the 401 case so pages
can render anonymously without try/catch boilerplate.
- /manga/[id] overview: pre-loads the user's bookmark list in its load
function and renders either:
- "★ Bookmarked" / "☆ Bookmark" toggle with aria-pressed when authed;
click POSTs or DELETEs and mutates a local working copy of the
bookmark list (optimistic UI without re-fetching);
- or a "Sign in to bookmark" link for anonymous users.
- /bookmarks page lists the current user's bookmarks (chapter-level
bookmarks link into the reader, manga-level back to the overview).
Anonymous users see a sign-in prompt instead of a 401 page.
E2E in e2e/bookmarks.spec.ts (3 cases): authed toggle round-trip
(bookmark, see in /bookmarks list, unbookmark); anonymous user gets the
sign-in CTA on the overview; anonymous /bookmarks shows the sign-in
prompt. Existing reader.spec.ts updated for the new
bookmark-signin/toggle test IDs.
Lockstep version bump to 0.7.0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
102
frontend/src/lib/api/bookmarks.test.ts
Normal file
102
frontend/src/lib/api/bookmarks.test.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
vi,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
type MockInstance
|
||||
} from 'vitest';
|
||||
import {
|
||||
createBookmark,
|
||||
deleteBookmark,
|
||||
listMyBookmarks,
|
||||
listMyBookmarksOrEmpty
|
||||
} from './bookmarks';
|
||||
|
||||
function ok(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
function noContent(): Response {
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
|
||||
function envelope(status: number, code: string, message: string): Response {
|
||||
return new Response(JSON.stringify({ error: { code, message } }), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
const bookmarkFixture = {
|
||||
id: 'b1',
|
||||
user_id: 'u1',
|
||||
manga_id: 'm1',
|
||||
chapter_id: null,
|
||||
page: null,
|
||||
created_at: '2026-01-01T00:00:00Z'
|
||||
};
|
||||
|
||||
describe('bookmarks api client', () => {
|
||||
let fetchSpy: MockInstance<typeof globalThis.fetch>;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchSpy = vi.spyOn(globalThis, 'fetch');
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('createBookmark POSTs JSON to /v1/bookmarks', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(ok(bookmarkFixture, 201));
|
||||
const b = await createBookmark({ manga_id: 'm1' });
|
||||
expect(b).toEqual(bookmarkFixture);
|
||||
const url = fetchSpy.mock.calls[0][0] as string;
|
||||
expect(url).toMatch(/\/v1\/bookmarks$/);
|
||||
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
||||
expect(init.method).toBe('POST');
|
||||
expect(JSON.parse(init.body as string)).toEqual({ manga_id: 'm1' });
|
||||
});
|
||||
|
||||
it('createBookmark surfaces 409 conflict', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(envelope(409, 'conflict', 'already bookmarked'));
|
||||
await expect(createBookmark({ manga_id: 'm1' })).rejects.toMatchObject({
|
||||
status: 409,
|
||||
code: 'conflict'
|
||||
});
|
||||
});
|
||||
|
||||
it('deleteBookmark DELETEs /v1/bookmarks/{id} and handles 204', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(noContent());
|
||||
await expect(deleteBookmark('b1')).resolves.toBeUndefined();
|
||||
const url = fetchSpy.mock.calls[0][0] as string;
|
||||
expect(url).toMatch(/\/v1\/bookmarks\/b1$/);
|
||||
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
||||
expect(init.method).toBe('DELETE');
|
||||
});
|
||||
|
||||
it('listMyBookmarks hits /v1/me/bookmarks and returns paged envelope', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
ok({ items: [bookmarkFixture], page: { limit: 50, offset: 0, total: null } })
|
||||
);
|
||||
const result = await listMyBookmarks();
|
||||
expect(result.items).toHaveLength(1);
|
||||
const url = fetchSpy.mock.calls[0][0] as string;
|
||||
expect(url).toMatch(/\/v1\/me\/bookmarks$/);
|
||||
});
|
||||
|
||||
it('listMyBookmarksOrEmpty returns empty page on 401', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(envelope(401, 'unauthenticated', 'unauthenticated'));
|
||||
const result = await listMyBookmarksOrEmpty();
|
||||
expect(result.items).toEqual([]);
|
||||
});
|
||||
|
||||
it('listMyBookmarksOrEmpty re-throws non-401', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(envelope(500, 'internal_error', 'oops'));
|
||||
await expect(listMyBookmarksOrEmpty()).rejects.toMatchObject({ status: 500 });
|
||||
});
|
||||
});
|
||||
60
frontend/src/lib/api/bookmarks.ts
Normal file
60
frontend/src/lib/api/bookmarks.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { ApiError, request, type Page } from './client';
|
||||
|
||||
export type Bookmark = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
manga_id: string;
|
||||
chapter_id: string | null;
|
||||
page: number | null;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type BookmarksPage = {
|
||||
items: Bookmark[];
|
||||
page: Page;
|
||||
};
|
||||
|
||||
export type NewBookmark = {
|
||||
manga_id: string;
|
||||
chapter_id?: string | null;
|
||||
page?: number | null;
|
||||
};
|
||||
|
||||
export async function createBookmark(input: NewBookmark): Promise<Bookmark> {
|
||||
return request<Bookmark>('/v1/bookmarks', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(input)
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteBookmark(id: string): Promise<void> {
|
||||
await request<void>(`/v1/bookmarks/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
export type ListMyOptions = { limit?: number; offset?: number };
|
||||
|
||||
export async function listMyBookmarks(
|
||||
opts: ListMyOptions = {}
|
||||
): Promise<BookmarksPage> {
|
||||
const params = new URLSearchParams();
|
||||
if (opts.limit != null) params.set('limit', String(opts.limit));
|
||||
if (opts.offset != null) params.set('offset', String(opts.offset));
|
||||
const qs = params.toString();
|
||||
return request<BookmarksPage>(`/v1/me/bookmarks${qs ? `?${qs}` : ''}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the user's bookmarks, or an empty page if they're not
|
||||
* authenticated. Re-throws any non-401 error.
|
||||
*/
|
||||
export async function listMyBookmarksOrEmpty(): Promise<BookmarksPage> {
|
||||
try {
|
||||
return await listMyBookmarks();
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 401) {
|
||||
return { items: [], page: { limit: 50, offset: 0, total: null } };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
50
frontend/src/routes/bookmarks/+page.svelte
Normal file
50
frontend/src/routes/bookmarks/+page.svelte
Normal file
@@ -0,0 +1,50 @@
|
||||
<script lang="ts">
|
||||
let { data } = $props();
|
||||
const authenticated = $derived(data.authenticated);
|
||||
const bookmarks = $derived(data.bookmarks);
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Bookmarks — Mangalord</title>
|
||||
</svelte:head>
|
||||
|
||||
<h1>Bookmarks</h1>
|
||||
|
||||
{#if !authenticated}
|
||||
<p data-testid="bookmarks-signin">
|
||||
<a href="/login">Sign in</a> to see your bookmarks.
|
||||
</p>
|
||||
{:else if bookmarks.length === 0}
|
||||
<p data-testid="bookmarks-empty">No bookmarks yet.</p>
|
||||
{:else}
|
||||
<ul class="bookmark-list" data-testid="bookmark-list">
|
||||
{#each bookmarks as b (b.id)}
|
||||
<li>
|
||||
{#if b.chapter_id}
|
||||
<a href="/manga/{b.manga_id}/chapter/{b.chapter_id}">
|
||||
Chapter bookmark
|
||||
{#if b.page}— page {b.page}{/if}
|
||||
</a>
|
||||
{:else}
|
||||
<a href="/manga/{b.manga_id}">Manga bookmark</a>
|
||||
{/if}
|
||||
<span class="created">{new Date(b.created_at).toLocaleDateString()}</span>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.bookmark-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
.bookmark-list li {
|
||||
padding: 0.5rem 0;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
.created {
|
||||
color: #888;
|
||||
margin-left: 0.5rem;
|
||||
}
|
||||
</style>
|
||||
17
frontend/src/routes/bookmarks/+page.ts
Normal file
17
frontend/src/routes/bookmarks/+page.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { listMyBookmarks } from '$lib/api/bookmarks';
|
||||
import { ApiError } from '$lib/api/client';
|
||||
import type { PageLoad } from './$types';
|
||||
|
||||
export const ssr = false;
|
||||
|
||||
export const load: PageLoad = async () => {
|
||||
try {
|
||||
const page = await listMyBookmarks();
|
||||
return { bookmarks: page.items, authenticated: true };
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 401) {
|
||||
return { bookmarks: [], authenticated: false };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
@@ -1,9 +1,41 @@
|
||||
<script lang="ts">
|
||||
import { fileUrl } from '$lib/api/client';
|
||||
import { createBookmark, deleteBookmark, type Bookmark } from '$lib/api/bookmarks';
|
||||
import { session } from '$lib/session.svelte';
|
||||
|
||||
let { data } = $props();
|
||||
const manga = $derived(data.manga);
|
||||
const chapters = $derived(data.chapters);
|
||||
|
||||
// Local working copy of the bookmark list — mutated optimistically
|
||||
// when the user toggles, instead of re-fetching from the server.
|
||||
// The route re-mounts on /manga/{id} → /manga/{other} navigation,
|
||||
// so capturing the initial value here is the desired behaviour.
|
||||
// svelte-ignore state_referenced_locally
|
||||
let bookmarks = $state<Bookmark[]>([...data.bookmarks]);
|
||||
|
||||
const mangaBookmark = $derived(
|
||||
bookmarks.find((b) => b.manga_id === manga.id && b.chapter_id === null) ?? null
|
||||
);
|
||||
|
||||
let busy = $state(false);
|
||||
|
||||
async function toggleBookmark() {
|
||||
if (!session.user) return;
|
||||
busy = true;
|
||||
try {
|
||||
if (mangaBookmark) {
|
||||
const id = mangaBookmark.id;
|
||||
await deleteBookmark(id);
|
||||
bookmarks = bookmarks.filter((b) => b.id !== id);
|
||||
} else {
|
||||
const b = await createBookmark({ manga_id: manga.id });
|
||||
bookmarks = [b, ...bookmarks];
|
||||
}
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
@@ -29,16 +61,24 @@
|
||||
{#if manga.description}
|
||||
<p class="description" data-testid="manga-description">{manga.description}</p>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="bookmark"
|
||||
disabled
|
||||
aria-disabled="true"
|
||||
title="Bookmarking lands in feat/bookmarks"
|
||||
data-testid="bookmark-placeholder"
|
||||
>
|
||||
☆ Bookmark
|
||||
</button>
|
||||
|
||||
{#if session.user}
|
||||
<button
|
||||
type="button"
|
||||
class="bookmark"
|
||||
class:active={mangaBookmark}
|
||||
onclick={toggleBookmark}
|
||||
disabled={busy}
|
||||
aria-pressed={mangaBookmark ? 'true' : 'false'}
|
||||
data-testid="bookmark-toggle"
|
||||
>
|
||||
{mangaBookmark ? '★ Bookmarked' : '☆ Bookmark'}
|
||||
</button>
|
||||
{:else}
|
||||
<a class="bookmark" href="/login" data-testid="bookmark-signin">
|
||||
Sign in to bookmark
|
||||
</a>
|
||||
{/if}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -89,7 +129,23 @@
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.bookmark {
|
||||
display: inline-block;
|
||||
margin-top: 0.5rem;
|
||||
padding: 0.4rem 0.75rem;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 4px;
|
||||
background: #fafafa;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.bookmark:focus-visible {
|
||||
outline: 2px solid #06f;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.bookmark.active {
|
||||
background: #ffeebb;
|
||||
border-color: #d6a800;
|
||||
}
|
||||
.chapter-list {
|
||||
padding-left: 1.5rem;
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { getManga } from '$lib/api/mangas';
|
||||
import { listChapters } from '$lib/api/chapters';
|
||||
import { listMyBookmarksOrEmpty } from '$lib/api/bookmarks';
|
||||
import type { PageLoad } from './$types';
|
||||
|
||||
export const ssr = false;
|
||||
|
||||
export const load: PageLoad = async ({ params }) => {
|
||||
const [manga, chapters] = await Promise.all([
|
||||
const [manga, chapters, bookmarks] = await Promise.all([
|
||||
getManga(params.id),
|
||||
listChapters(params.id)
|
||||
listChapters(params.id),
|
||||
listMyBookmarksOrEmpty()
|
||||
]);
|
||||
return { manga, chapters: chapters.items };
|
||||
return { manga, chapters: chapters.items, bookmarks: bookmarks.items };
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user