fix: bookmark toggle is optimistic and no longer fails silently
The detail-page bookmark toggle awaited the round-trip before updating and had no catch — a failed create/delete threw unhandled and the user saw nothing. It now flips optimistically (placeholder reconciled with the server row on success), rolls back on error, and surfaces a toast, matching the sibling like/dislike buttons. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -18,6 +18,7 @@
|
||||
import { listTags, type Tag } from '$lib/api/tags';
|
||||
import type { ContentWarning } from '$lib/api/page_tags';
|
||||
import { session } from '$lib/session.svelte';
|
||||
import { toast } from '$lib/toast.svelte';
|
||||
import Chip from '$lib/components/Chip.svelte';
|
||||
import MangaCard from '$lib/components/MangaCard.svelte';
|
||||
import ReactionButtons from '$lib/components/ReactionButtons.svelte';
|
||||
@@ -155,17 +156,36 @@
|
||||
});
|
||||
|
||||
async function toggleBookmark() {
|
||||
if (!session.user) return;
|
||||
if (!session.user || busy) return;
|
||||
const existing = mangaBookmark;
|
||||
// Snapshot for rollback — the update below is applied optimistically
|
||||
// so the button flips instantly, then reconciled/reverted.
|
||||
const snapshot = bookmarks;
|
||||
busy = true;
|
||||
try {
|
||||
if (mangaBookmark) {
|
||||
const id = mangaBookmark.id;
|
||||
await deleteBookmark(id);
|
||||
bookmarks = bookmarks.filter((b) => b.id !== id);
|
||||
if (existing) {
|
||||
bookmarks = bookmarks.filter((b) => b.id !== existing.id);
|
||||
await deleteBookmark(existing.id);
|
||||
} else {
|
||||
// Temporary placeholder so the derived `mangaBookmark` flips
|
||||
// immediately; swapped for the server row (with its real id)
|
||||
// once the POST returns.
|
||||
const tempId = `optimistic-${crypto.randomUUID()}`;
|
||||
const placeholder: Bookmark = {
|
||||
id: tempId,
|
||||
user_id: session.user.id,
|
||||
manga_id: manga.id,
|
||||
chapter_id: null,
|
||||
page: null,
|
||||
created_at: new Date().toISOString()
|
||||
};
|
||||
bookmarks = [placeholder, ...bookmarks];
|
||||
const b = await createBookmark({ manga_id: manga.id });
|
||||
bookmarks = [b, ...bookmarks];
|
||||
bookmarks = [b, ...bookmarks.filter((x) => x.id !== tempId)];
|
||||
}
|
||||
} catch {
|
||||
bookmarks = snapshot;
|
||||
toast.error(existing ? 'Could not remove bookmark.' : 'Could not add bookmark.');
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user