Files
Showy/react_frontend/src/pages/CollectionDetailsPage.tsx
T
X4Lo 72600cbc5d Fix collection images and entry settings toggles
- Show the uploaded backdrop on the collection details page; it only
  looked at the TMDB backdrop and ignored the collection's media
- Fall back to the first entry's poster for collections without a poster
  on both the collections grid and the details page
- Read the live entry from the library store in EntrySettingsDialog so
  toggles reflect the new value instead of a stale prop snapshot
2026-11-03 16:25:12 +00:00

361 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useState, useMemo, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
useCollection,
useDeleteCollection,
useGetCollectionParts,
useRemoveEntryFromCollection,
} from "@/hooks/useCollections";
import { EntryLibraryGrid } from "@/components/entries/EntryLibraryGrid";
import {
getCollectionDisplayBackdropUrl,
getCollectionDisplayPosterUrl,
} from "@/lib/collection-media";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
Star,
MoreVertical,
Pencil,
Download,
Trash2,
ArrowUp,
ArrowDown,
Eye,
EyeOff,
} from "lucide-react";
import { CollectionEditDialog } from "@/components/dialogs/CollectionEditDialog";
import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
import { toast } from "sonner";
import type { Entry } from "@/types";
import {
useCollectionSortStore,
type CollectionSortField,
type SortDir,
} from "@/stores/useCollectionSortStore";
export function CollectionDetailsPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { data: collection, isLoading, isError } = useCollection(Number(id));
const [showEditDialog, setShowEditDialog] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const collectionSortPrefs = useCollectionSortStore((s) => s.prefs);
const setSortPref = useCollectionSortStore((s) => s.setSort);
const setHideUnseen = useCollectionSortStore((s) => s.setHideUnseen);
const collectionId = Number(id);
const sortPref = collectionSortPrefs[collectionId];
const sortField: CollectionSortField = sortPref?.field ?? "order";
const sortDir: SortDir = sortPref?.dir ?? "asc";
const hideUnseen = sortPref?.hideUnseen ?? false;
const deleteCollection = useDeleteCollection();
const getCollectionParts = useGetCollectionParts();
const removeEntryFromCollection = useRemoveEntryFromCollection();
const entries = useMemo(
() => (collection?.entries || []).map((e) => ({ ...e, isInLibrary: true })),
[collection?.entries],
);
const sortedEntries = useMemo(() => {
return [...entries].sort((a, b) => {
let cmp = 0;
switch (sortField) {
case "order": {
const oa =
(a as Entry & { UserCollectionEntry?: { order: number } })
.UserCollectionEntry?.order ?? 0;
const ob =
(b as Entry & { UserCollectionEntry?: { order: number } })
.UserCollectionEntry?.order ?? 0;
cmp = oa - ob;
break;
}
case "year": {
const ya = a.release_date
? new Date(a.release_date).getFullYear()
: 0;
const yb = b.release_date
? new Date(b.release_date).getFullYear()
: 0;
cmp = ya - yb;
break;
}
case "title":
cmp = (a.title || "").localeCompare(b.title || "");
break;
case "rating": {
const ra =
a.entryRatings?.user_rating || a.entryRatings?.tmdb_rating || 0;
const rb =
b.entryRatings?.user_rating || b.entryRatings?.tmdb_rating || 0;
cmp = ra - rb;
break;
}
}
return sortDir === "asc" ? cmp : -cmp;
});
}, [entries, sortField, sortDir]);
// Uploaded backdrop wins, then TMDB backdrop, then the first entry's backdrop
const backdropUrl = useMemo(
() => (collection ? getCollectionDisplayBackdropUrl(collection) : null),
[collection],
);
const handleSort = (field: CollectionSortField) => {
if (field === sortField) {
setSortPref(collectionId, field, sortDir === "asc" ? "desc" : "asc");
} else {
setSortPref(collectionId, field, field === "rating" ? "desc" : "asc");
}
};
// ── Computed stats (from already-fetched data) ──
const stats = useMemo(() => {
const movies = entries.filter((e) => !e.is_tvseries);
const tvEntries = entries.filter((e) => e.is_tvseries);
const seasonCount = tvEntries.reduce(
(sum, e) => sum + (e.seasons?.length || 0),
0,
);
const episodeCount = tvEntries.reduce(
(sum, e) =>
sum +
(e.seasons?.reduce((s, season) => s + (season.episode_count || 0), 0) ||
0),
0,
);
const typeParts: string[] = [];
if (movies.length > 0) typeParts.push(`${movies.length} movies`);
if (tvEntries.length > 0) typeParts.push(`${tvEntries.length} series`);
const typeStr = typeParts.join(" & ");
const subParts: string[] = [];
if (seasonCount > 0) subParts.push(`${seasonCount} seasons`);
if (episodeCount > 0) subParts.push(`${episodeCount} episodes`);
const subStr = subParts.length > 0 ? ` (${subParts.join("/")})` : "";
const summary = `${entries.length} entries - ${typeStr}${subStr}`;
const watchMinutes = entries.reduce((sum, e) => {
if (e.is_tvseries) {
const eps =
e.seasons?.reduce(
(s, season) => s + (season.episode_count || 0),
0,
) || 0;
const epRuntime = e.runtime || 42;
return sum + eps * epRuntime;
}
return sum + (e.runtime || 0);
}, 0);
const hours = Math.floor(watchMinutes / 60);
const mins = watchMinutes % 60;
const watchTime = hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
return { summary, watchTime };
}, [entries]);
// Handle error redirect in useEffect (not during render)
useEffect(() => {
if (!isLoading && (isError || (!collection && !isLoading))) {
toast.error("Collection not found");
navigate("/collections", { replace: true });
}
}, [isLoading, isError, collection, navigate]);
if (isLoading) {
return (
<div className="space-y-6">
<Skeleton className="h-48 w-full rounded-xl" />
<Skeleton className="h-8 w-64" />
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{Array.from({ length: 6 }).map((_, i) => (
<Skeleton key={i} className="aspect-2/3 w-full rounded-lg" />
))}
</div>
</div>
);
}
if (!collection) return null;
const handleDelete = () => {
deleteCollection.mutate(collection.id, {
onSuccess: () => navigate("/collections", { replace: true }),
});
};
const handleGetParts = () => {
getCollectionParts.mutate(collection.id);
};
return (
<div className="space-y-6 animate-page-enter">
{/* Hero banner */}
<div className="relative overflow-hidden rounded-xl">
{backdropUrl ? (
<img
src={backdropUrl}
alt={collection.name}
className="h-48 w-full object-cover sm:h-64"
/>
) : (
<div className="h-48 w-full bg-linear-to-br from-primary/15 to-primary/5 sm:h-64" />
)}
<div className="absolute inset-0 bg-linear-to-t from-background via-background/60 to-transparent" />
{/* Quick action menu - top right */}
<div className="absolute top-3 right-3">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="icon" className="h-8 w-8">
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setShowEditDialog(true)}>
<Pencil className="mr-2 h-4 w-4" />
Edit
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleGetParts}
disabled={getCollectionParts.isPending}
>
<Download className="mr-2 h-4 w-4" />
{getCollectionParts.isPending ? "Fetching..." : "Get All Parts"}
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onClick={() => setShowDeleteConfirm(true)}
>
<Trash2 className="mr-2 h-4 w-4" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="absolute bottom-0 left-0 right-0 flex items-end p-6">
<div className="flex items-end gap-4">
<img
src={getCollectionDisplayPosterUrl(collection)}
alt={collection.name}
className="h-32 w-auto rounded-lg shadow-lg sm:h-40"
/>
<div className="space-y-1">
<h1 className="text-2xl font-bold text-white sm:text-3xl">
{collection.name}
</h1>
{collection.description && (
<p className="max-w-xl text-sm text-white/80 line-clamp-3">
{collection.description}
</p>
)}
<div className="flex items-center gap-3 flex-wrap text-sm text-white/60">
<span>
{stats.summary} ~{stats.watchTime}
</span>
{collection.user_rating != null &&
collection.user_rating > 0 && (
<div className="flex items-center gap-1">
<Star className="h-4 w-4 fill-yellow-400 text-yellow-400" />
<span className="text-sm font-medium text-white">
{collection.user_rating}/10
</span>
</div>
)}
</div>
</div>
</div>
{/* Sort – bottom right */}
<div className="ml-auto flex items-center gap-1 self-end">
{entries.length > 1 && (
<>
{(["order", "year", "title", "rating"] as const).map(
(field) => (
<Button
key={field}
variant={sortField === field ? "secondary" : "ghost"}
size="sm"
className="h-7 text-xs capitalize gap-1"
onClick={() => handleSort(field)}
>
{field}
{sortField === field &&
(sortDir === "asc" ? (
<ArrowUp className="h-3 w-3" />
) : (
<ArrowDown className="h-3 w-3" />
))}
</Button>
),
)}
<span className="mx-1 h-5 w-px bg-white/30" />
</>
)}
<Button
variant={hideUnseen ? "secondary" : "ghost"}
size="sm"
className="h-7 text-xs gap-1"
title={
hideUnseen ? "Show all entries" : "Gray out unseen entries"
}
onClick={() => setHideUnseen(collectionId, !hideUnseen)}
>
{hideUnseen ? (
<Eye className="h-3 w-3" />
) : (
<EyeOff className="h-3 w-3" />
)}
{hideUnseen ? "Show seen" : "Show all"}
</Button>
</div>
</div>
</div>
{/* Entries grid */}
<EntryLibraryGrid
entries={sortedEntries}
isLoading={false}
collectionId={collection.id}
grayOutUnseen={hideUnseen}
onRemoveFromCollection={(entryId) =>
removeEntryFromCollection.mutate({
collectionId: collection.id,
entryId,
})
}
/>
{/* Edit dialog */}
{showEditDialog && (
<CollectionEditDialog
open={showEditDialog}
onOpenChange={setShowEditDialog}
collection={collection}
/>
)}
{/* Delete confirmation */}
<ConfirmDialog
open={showDeleteConfirm}
onOpenChange={setShowDeleteConfirm}
title="Delete Collection"
description={`Are you sure you want to delete "${collection.name}"? This action cannot be undone.`}
confirmLabel="Delete"
onConfirm={handleDelete}
variant="destructive"
/>
</div>
);
}