Complete frontend refactoring: UI enhancements, pagination, filtering, search architecture, and data management improvements

# Phase 1: Feature Implementation
- Add "Create new..." option in `AddEntryToCollectionDialog` for inline collection creation with auto-select
- Implement lazy loading pagination with IntersectionObserver for Watchlist, Collections, and Media pages
- Add reusable useDebounce hook (300-400ms) and apply to all search inputs across pages
- Reset scroll position to top when switching between sidebar navigation pages via useLocation()
- Reorganize MediaPage with horizontal control layout, add Media Type filter (All/Audio/Video), and Custom Media filter (Show All/Official Only/Custom Only)
- Add three-dot menu (MoreHorizontal icon) to collection cards with Edit/Delete options and "Get all parts" feature
- Replace numeric rating input with interactive star rating component in EditCollectionDialog (0-10 stars with half-star support)
- Display entry type badges ("Movie" / "TV Series") on home page trending/popular sections and search results
- Create PeopleSearchResult component with profile images; integrate useTmdbSearchPeople hook linking to `/people/tmdb/:tmdbId`
- Add TMDB Rating and User Rating filters to Library page with range sliders (0-10, step 1) and state persistence in useLibraryStore
- Add All/Movies/TV Series type filter to Watchlist page with filtered count display
- Improve People Details page mobile UI: optimize header, info section sizing, and filmography card layouts for touch

# Phase 2: Architecture Refactoring & Bug Fixes
- Fix scroll-to-top on sidebar navigation by constraining AppLayout root to `h-screen overflow-hidden` so `<main>` becomes proper scroll container
- Extract search from HomePage into dedicated SearchPage component with `/search` route, debounced input, and URL query sync via SearchParams
- Add Search nav item with icon to sidebar for easy search access
- HomePage search input now navigates to `/search?q=...` instead of handling inline, separating concerns and enabling search bookmarking
- Entry type pill badges now conditionally render via `showTypeBadge` prop on EntryCard—only SearchPage passes this to prevent display on home/discover pages
- Fix people ID bug: people search results now link to `/people/tmdb/:tmdbId` (TMDB redirect route) instead of `/people/:id`, correctly mapping TMDB IDs to local database IDs through PersonTmdbRedirectPage
- Enhance People Details filmography sorting: "Not in Library" section now detects self roles (self/themselves/himself/herself) and sorts non-self by release date (new→old) with all self roles pushed to end of list

# Summary
- Created new files: SearchPage.tsx, useDebounce.ts
This commit is contained in:
Mohammed Abad committed 2026-04-12 01:33:00 +01:00
1 parent d28b4caa7e
commit 9a8ee181e5
23 files changed
+680 -188

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
# Copilot Instructions
## Mandatory Task Completion Rule
After completing ANY task requested by the user, you MUST update the file `changes.md`.
### Required Format
Append a new section at the end of `changes.md` using this exact format:
### Tasks XXX
```md
<commit message>
- <change 1>
- <change 2>
- <change 3>
```
### Rules
- Replace `XXX` with the task number provided by the user (example: `025`).
- The first line inside the code block must be a short commit-style message (imperative tone).
- The bullet list must include all important modifications made.
- Do NOT overwrite previous entries: always APPEND.
- If `changes.md` does not exist, create it.
- If no task number is provided, use the next available number based on the last entry in the file.
- Always ensure formatting matches exactly (heading + code block + bullets).
+1
View File
@@ -26,3 +26,4 @@ dist-ssr
# other
goal.md
prompt.md
changes.md
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>react_frontend</title>
<title>Showy</title>
</head>
<body>
<div id="root"></div>
+3 -4
View File
@@ -690,9 +690,9 @@
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.0.tgz",
"integrity": "sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==",
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
"integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
"dev": true,
"license": "MIT",
"optional": true,
@@ -4654,7 +4654,6 @@
"resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz",
"integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==",
"license": "MIT",
"peer": true,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/immer"
+3
View File
@@ -29,6 +29,9 @@ export const collectionsApi = {
delete: (id: number) =>
api.delete(`/collections/${id}`).then((r) => r.data),
getCollectionParts: (id: number) =>
api.put<Collection>(`/collections/${id}/parts`).then((r) => normalizeCollection(r.data)),
addEntry: (collectionId: number, entryId: number) =>
api
.post(`/collections/${collectionId}/entries/${entryId}`, {})
@@ -1,3 +1,4 @@
import { useCallback, useRef, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { getCollectionPosterUrl } from '@/lib/media-utils';
import { Skeleton } from '@/components/ui/skeleton';
@@ -37,12 +38,35 @@ export function CollectionCardSkeleton() {
interface CollectionsGridProps {
collections: Collection[];
isLoading?: boolean;
hasMore?: boolean;
onLoadMore?: () => void;
}
export function CollectionsGrid({
collections,
isLoading,
hasMore,
onLoadMore,
}: CollectionsGridProps) {
const observerRef = useRef<IntersectionObserver | null>(null);
const lastItemRef = useCallback(
(node: HTMLDivElement | null) => {
if (isLoading) return;
if (observerRef.current) observerRef.current.disconnect();
observerRef.current = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && hasMore && onLoadMore) {
onLoadMore();
}
});
if (node) observerRef.current.observe(node);
},
[isLoading, hasMore, onLoadMore]
);
useEffect(() => {
return () => observerRef.current?.disconnect();
}, []);
if (isLoading) {
return (
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
@@ -66,6 +90,7 @@ export function CollectionsGrid({
{collections.map((collection, index) => (
<div
key={collection.id}
ref={index === collections.length - 1 ? lastItemRef : undefined}
className="animate-card-enter"
style={{ animationDelay: `${Math.min(index * 30, 300)}ms` }}
>
@@ -8,10 +8,13 @@ import {
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { Plus, Loader2 } from 'lucide-react';
import { useCollections } from '@/hooks/useCollections';
import { useQueryClient } from '@tanstack/react-query';
import { collectionsApi } from '@/api/collections';
import { collectionKeys } from '@/hooks/useCollections';
import { toast } from 'sonner';
import type { Collection } from '@/types';
interface AddEntryToCollectionDialogProps {
@@ -27,6 +30,7 @@ export function AddEntryToCollectionDialog({
}: AddEntryToCollectionDialogProps) {
const [search, setSearch] = useState('');
const [pending, setPending] = useState<Set<number>>(new Set());
const [creating, setCreating] = useState(false);
const { data: allCollections = [] } = useCollections();
const queryClient = useQueryClient();
@@ -34,6 +38,12 @@ export function AddEntryToCollectionDialog({
c.name.toLowerCase().includes(search.toLowerCase())
);
const showCreateOption =
search.trim().length > 0 &&
!allCollections.some(
(c) => c.name.toLowerCase() === search.trim().toLowerCase()
);
const isInCollection = (collectionId: number) =>
allCollections
.find((c) => c.id === collectionId)
@@ -75,6 +85,23 @@ export function AddEntryToCollectionDialog({
}
};
const handleCreate = async () => {
const name = search.trim();
if (!name) return;
setCreating(true);
try {
const newCollection = await collectionsApi.create({ name, is_user_collection: true } as Partial<Collection>);
await collectionsApi.addEntry(newCollection.id, entryId);
await queryClient.invalidateQueries({ queryKey: collectionKeys.all });
toast.success(`Created "${name}" and added entry`);
setSearch('');
} catch {
toast.error('Failed to create collection');
} finally {
setCreating(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
@@ -82,12 +109,27 @@ export function AddEntryToCollectionDialog({
<DialogTitle>Add to Collection</DialogTitle>
</DialogHeader>
<Input
placeholder="Search collections..."
placeholder="Search or create collection..."
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<ScrollArea className="h-64">
<div className="space-y-2 pr-4">
{showCreateOption && (
<Button
variant="ghost"
className="flex w-full items-center justify-start gap-2 rounded-lg p-2 text-sm text-primary hover:bg-accent/50"
disabled={creating}
onClick={handleCreate}
>
{creating ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Plus className="h-4 w-4" />
)}
Create "{search.trim()}"
</Button>
)}
{filtered.map((collection) => {
const checked = isInCollection(collection.id);
const loading = pending.has(collection.id);
@@ -107,7 +149,7 @@ export function AddEntryToCollectionDialog({
</label>
);
})}
{filtered.length === 0 && (
{filtered.length === 0 && !showCreateOption && (
<p className="py-4 text-center text-sm text-muted-foreground">
No collections found.
</p>
@@ -10,7 +10,7 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { ImageIcon } from 'lucide-react';
import { ImageIcon, Star } from 'lucide-react';
import { useUpdateCollection } from '@/hooks/useCollections';
import type { Collection } from '@/types';
@@ -28,8 +28,9 @@ export function CollectionEditDialog({
const [name, setName] = useState(collection.name);
const [description, setDescription] = useState(collection.description || '');
const [userRating, setUserRating] = useState(
collection.user_rating?.toString() || ''
collection.user_rating ?? 0
);
const [hoveredStar, setHoveredStar] = useState<number | null>(null);
const [posterFile, setPosterFile] = useState<File | null>(null);
const [backdropFile, setBackdropFile] = useState<File | null>(null);
const [posterPreview, setPosterPreview] = useState<string | null>(null);
@@ -62,7 +63,7 @@ export function CollectionEditDialog({
const formData = new FormData();
formData.append('name', name);
formData.append('description', description);
formData.append('userRating', userRating || '0');
formData.append('userRating', String(userRating || 0));
if (posterFile) {
formData.append('poster', posterFile);
@@ -105,16 +106,35 @@ export function CollectionEditDialog({
</div>
<div className="space-y-2">
<Label htmlFor="col-rating">User Rating (0-10)</Label>
<Input
id="col-rating"
type="number"
min={0}
max={10}
step={0.1}
value={userRating}
onChange={(e) => setUserRating(e.target.value)}
/>
<Label>User Rating</Label>
<div className="flex items-center gap-2">
<div className="flex gap-1">
{Array.from({ length: 10 }, (_, i) => i + 1).map((star) => {
const displayRating = hoveredStar ?? userRating;
return (
<button
key={star}
type="button"
className="transition-transform hover:scale-125 focus:outline-none"
onMouseEnter={() => setHoveredStar(star)}
onMouseLeave={() => setHoveredStar(null)}
onClick={() => setUserRating(star === userRating ? 0 : star)}
>
<Star
className={`h-5 w-5 transition-colors ${
star <= displayRating
? 'fill-yellow-400 text-yellow-400'
: 'text-muted-foreground/30'
}`}
/>
</button>
);
})}
</div>
<span className="text-sm text-muted-foreground tabular-nums">
{userRating > 0 ? `${userRating}/10` : '—'}
</span>
</div>
</div>
{/* Media uploads */}
@@ -13,9 +13,10 @@ import type { Entry, TmdbEntry } from '@/types';
interface EntryCardProps {
entry?: Entry;
tmdbEntry?: TmdbEntry;
showTypeBadge?: boolean;
}
export function EntryCard({ entry, tmdbEntry }: EntryCardProps) {
export function EntryCard({ entry, tmdbEntry, showTypeBadge }: EntryCardProps) {
const [showConfirm, setShowConfirm] = useState(false);
const createEntry = useCreateEntry();
const deleteEntry = useDeleteEntry();
@@ -105,6 +106,16 @@ export function EntryCard({ entry, tmdbEntry }: EntryCardProps) {
<Star className="absolute right-2 top-2 h-4 w-4 fill-yellow-400 text-yellow-400" />
)}
{/* Entry type pill */}
{showTypeBadge && tmdbEntry && (
<Badge
variant="secondary"
className="absolute bottom-2 right-2 text-[10px] px-1.5 py-0.5 opacity-90 z-10 pointer-events-none"
>
{isTv ? 'TV Series' : 'Movie'}
</Badge>
)}
{/* Hover overlay */}
<div className="absolute inset-0 flex flex-col justify-end bg-gradient-to-t from-black/90 via-black/40 to-transparent opacity-0 transition-opacity duration-200 group-hover:opacity-100">
<div className="p-3 space-y-1">
@@ -1,5 +1,5 @@
import { Outlet } from 'react-router-dom';
import { useState } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
import { useState, useRef, useEffect } from 'react';
import { Menu } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
@@ -12,9 +12,15 @@ import { Sidebar, MobileSidebarContent } from './Sidebar';
export function AppLayout() {
const [mobileOpen, setMobileOpen] = useState(false);
const mainRef = useRef<HTMLElement>(null);
const { pathname } = useLocation();
useEffect(() => {
mainRef.current?.scrollTo(0, 0);
}, [pathname]);
return (
<div className="flex min-h-screen">
<div className="flex h-screen overflow-hidden">
{/* Desktop sidebar */}
<div className="hidden md:block">
<Sidebar />
@@ -38,7 +44,7 @@ export function AppLayout() {
</SheetContent>
</Sheet>
<main className="flex-1 overflow-y-auto md:ml-56">
<main ref={mainRef} className="flex-1 overflow-y-auto md:ml-56">
<div className="container mx-auto px-4 py-4 pt-18 md:px-6 md:py-6 md:pt-6">
<Outlet />
</div>
@@ -12,6 +12,7 @@ import {
Moon,
Sun,
Film,
// Search,
} from 'lucide-react';
import { useThemeStore } from '@/stores/useThemeStore';
import { Button } from '@/components/ui/button';
@@ -25,6 +26,7 @@ import {
const mainNav = [
{ to: '/dashboard', icon: LayoutDashboard, label: 'Dashboard' },
{ to: '/', icon: Home, label: 'Home' },
// { to: '/search', icon: Search, label: 'Search' },
];
const libraryNav = [
@@ -38,3 +38,34 @@ export function useUpdateCollection() {
},
});
}
export function useDeleteCollection() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: number) => collectionsApi.delete(id),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: collectionKeys.all });
toast.success('Collection deleted');
},
onError: () => {
toast.error('Failed to delete collection');
},
});
}
export function useGetCollectionParts() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: number) => collectionsApi.getCollectionParts(id),
onSuccess: (_data, id) => {
queryClient.invalidateQueries({ queryKey: collectionKeys.detail(id) });
queryClient.invalidateQueries({ queryKey: collectionKeys.all });
toast.success('Collection parts fetched');
},
onError: () => {
toast.error('Failed to fetch collection parts');
},
});
}
+12
View File
@@ -0,0 +1,12 @@
import { useState, useEffect } from 'react';
export function useDebounce<T>(value: T, delay = 300): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
@@ -1,18 +1,30 @@
import { useState } from 'react';
import { useParams } from 'react-router-dom';
import { useCollection } from '@/hooks/useCollections';
import { useParams, useNavigate } from 'react-router-dom';
import { useCollection, useDeleteCollection, useGetCollectionParts } from '@/hooks/useCollections';
import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid';
import { getCollectionPosterUrl } from '@/lib/media-utils';
import { getTmdbImageUrl } from '@/lib/api';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Star, Pencil } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Star, MoreVertical, Pencil, Download, Trash2 } from 'lucide-react';
import { CollectionEditDialog } from '@/components/dialogs/CollectionEditDialog';
import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog';
import { toast } from 'sonner';
export function CollectionDetailsPage() {
const { id } = useParams<{ id: string }>();
const { data: collection, isLoading } = useCollection(Number(id));
const navigate = useNavigate();
const { data: collection, isLoading, isError } = useCollection(Number(id));
const [showEditDialog, setShowEditDialog] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const deleteCollection = useDeleteCollection();
const getCollectionParts = useGetCollectionParts();
if (isLoading) {
return (
@@ -28,12 +40,10 @@ export function CollectionDetailsPage() {
);
}
if (!collection) {
return (
<div className="flex h-40 items-center justify-center text-muted-foreground">
Collection not found.
</div>
);
if (!collection || isError) {
toast.error('Collection not found');
navigate('/collections', { replace: true });
return null;
}
const backdropUrl = collection.backdrop_path
@@ -45,6 +55,16 @@ export function CollectionDetailsPage() {
isInLibrary: true,
}));
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 */}
@@ -59,7 +79,36 @@ export function CollectionDetailsPage() {
<div className="h-48 w-full bg-muted sm:h-64" />
)}
<div className="absolute inset-0 bg-gradient-to-t from-background via-background/60 to-transparent" />
<div className="absolute bottom-0 left-0 right-0 flex items-end justify-between p-6">
{/* 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={getCollectionPosterUrl(collection)}
@@ -90,15 +139,6 @@ export function CollectionDetailsPage() {
</div>
</div>
</div>
<Button
variant="secondary"
size="sm"
className="shrink-0"
onClick={() => setShowEditDialog(true)}
>
<Pencil className="mr-1 h-4 w-4" />
Edit
</Button>
</div>
</div>
@@ -113,6 +153,17 @@ export function CollectionDetailsPage() {
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>
);
}
+21 -5
View File
@@ -1,14 +1,19 @@
import { useState, useMemo } from 'react';
import { useState, useMemo, useCallback, useEffect } from 'react';
import { useCollections } from '@/hooks/useCollections';
import { useDebounce } from '@/hooks/useDebounce';
import { CollectionsGrid } from '@/components/collections/CollectionsGrid';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Search } from 'lucide-react';
const PAGE_SIZE = 24;
export function CollectionsPage() {
const { data: collections = [], isLoading } = useCollections();
const [search, setSearch] = useState('');
const debouncedSearch = useDebounce(search, 300);
const [filter, setFilter] = useState<'all' | 'official' | 'custom'>('all');
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const filtered = useMemo(() => {
let result = collections;
@@ -19,13 +24,24 @@ export function CollectionsPage() {
result = result.filter((c) => c.is_user_collection);
}
if (search) {
const q = search.toLowerCase();
if (debouncedSearch) {
const q = debouncedSearch.toLowerCase();
result = result.filter((c) => c.name.toLowerCase().includes(q));
}
return result;
}, [collections, filter, search]);
}, [collections, filter, debouncedSearch]);
useEffect(() => {
setVisibleCount(PAGE_SIZE);
}, [filter, debouncedSearch]);
const paginatedCollections = useMemo(
() => filtered.slice(0, visibleCount),
[filtered, visibleCount]
);
const hasMore = visibleCount < filtered.length;
const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []);
return (
<div className="space-y-6 animate-page-enter">
@@ -54,7 +70,7 @@ export function CollectionsPage() {
</div>
</div>
<CollectionsGrid collections={filtered} isLoading={isLoading} />
<CollectionsGrid collections={paginatedCollections} isLoading={isLoading} hasMore={hasMore} onLoadMore={loadMore} />
</div>
);
}
@@ -254,13 +254,13 @@ export function EntryDetailsPage() {
<>
<span>•</span>
{watchHistory.length === 1 ? (
<span>seen {formatDate(watchHistory[0].date_seen)}</span>
<span>Seen {formatDate(watchHistory[0].date_seen)}</span>
) : (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span className="cursor-default underline decoration-dotted">
seen {watchHistory.length} times
Seen {watchHistory.length} times
</span>
</TooltipTrigger>
<TooltipContent>
@@ -353,7 +353,7 @@ export function EntryDetailsPage() {
</>
)}
{watchHistory.length > 0 && (
{/* {watchHistory.length > 0 && (
<>
<Separator />
<EpisodeWatchHistory
@@ -363,7 +363,7 @@ export function EntryDetailsPage() {
}
/>
</>
)}
)} */}
</div>
</div>
+45 -78
View File
@@ -6,30 +6,18 @@ import {
useTopRatedMovies,
useTopRatedTv,
useUpcomingMovies,
useTmdbSearch,
} from '@/hooks/useTmdb';
import { useLibrary } from '@/hooks/useEntries';
import { TrendingGrid } from '@/components/entries/TrendingGrid';
import { TrendingSlider } from '@/components/entries/TrendingSlider';
import { Input } from '@/components/ui/input';
import { useState, useEffect, useRef } from 'react';
import { Search } from 'lucide-react';
import { EntryCard } from '@/components/entries/EntryCard';
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
export function HomePage() {
const navigate = useNavigate();
const [searchInput, setSearchInput] = useState('');
const [debouncedQuery, setDebouncedQuery] = useState('');
const debounceRef = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => {
setDebouncedQuery(searchInput);
}, 400);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [searchInput]);
// Pre-load library
useLibrary();
@@ -41,7 +29,6 @@ export function HomePage() {
const topRatedMovies = useTopRatedMovies();
const topRatedTv = useTopRatedTv();
const upcomingMovies = useUpcomingMovies();
const searchResults = useTmdbSearch(debouncedQuery);
const trendingMovieEntries = trendingMovies.data?.pages.flatMap((p) => p.results) ?? [];
const trendingTvEntries = trendingTv.data?.pages.flatMap((p) => p.results) ?? [];
@@ -50,87 +37,67 @@ export function HomePage() {
const topRatedMovieEntries = topRatedMovies.data?.pages.flatMap((p) => p.results) ?? [];
const topRatedTvEntries = topRatedTv.data?.pages.flatMap((p) => p.results) ?? [];
const upcomingMovieEntries = upcomingMovies.data?.pages.flatMap((p) => p.results) ?? [];
const searchEntries = searchResults.data?.pages.flatMap((p) => p.results) ?? [];
const isSearching = debouncedQuery.length > 0;
const handleSearchSubmit = () => {
const q = searchInput.trim();
if (q) {
navigate(`/search?q=${encodeURIComponent(q)}`);
}
};
return (
<div className="space-y-8 animate-page-enter">
{/* Trending Slider Hero */}
{!isSearching && (
<TrendingSlider
entries={trendingMovieEntries}
isLoading={trendingMovies.isLoading}
/>
)}
<TrendingSlider
entries={trendingMovieEntries}
isLoading={trendingMovies.isLoading}
/>
{/* Search */}
<div className="relative max-w-md">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search movies & TV shows..."
placeholder="Search movies, TV shows & people..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') handleSearchSubmit();
}}
className="pl-10"
/>
</div>
{isSearching ? (
<div className="space-y-4">
<h2 className="text-xl font-semibold">
Search Results for "{debouncedQuery}"
</h2>
{searchEntries.length === 0 && !searchResults.isLoading ? (
<p className="text-muted-foreground">No results found.</p>
) : (
<div className="grid grid-cols-2 gap-3 sm:gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
{searchEntries.map((entry, index) => (
<div
key={entry.id}
className="animate-card-enter"
style={{ animationDelay: `${Math.min(index * 30, 300)}ms` }}
>
<EntryCard tmdbEntry={entry} />
</div>
))}
</div>
)}
</div>
) : (
<>
<TrendingGrid
title="Trending"
movieEntries={trendingMovieEntries}
tvEntries={trendingTvEntries}
isLoading={trendingMovies.isLoading || trendingTv.isLoading}
category="trending"
/>
<TrendingGrid
title="Trending"
movieEntries={trendingMovieEntries}
tvEntries={trendingTvEntries}
isLoading={trendingMovies.isLoading || trendingTv.isLoading}
category="trending"
/>
<TrendingGrid
title="Popular"
movieEntries={popularMovieEntries}
tvEntries={popularTvEntries}
isLoading={popularMovies.isLoading || popularTv.isLoading}
category="popular"
/>
<TrendingGrid
title="Popular"
movieEntries={popularMovieEntries}
tvEntries={popularTvEntries}
isLoading={popularMovies.isLoading || popularTv.isLoading}
category="popular"
/>
<TrendingGrid
title="Top Rated"
movieEntries={topRatedMovieEntries}
tvEntries={topRatedTvEntries}
isLoading={topRatedMovies.isLoading || topRatedTv.isLoading}
category="top-rated"
/>
<TrendingGrid
title="Top Rated"
movieEntries={topRatedMovieEntries}
tvEntries={topRatedTvEntries}
isLoading={topRatedMovies.isLoading || topRatedTv.isLoading}
category="top-rated"
/>
<TrendingGrid
title="Upcoming"
movieEntries={upcomingMovieEntries}
tvEntries={[]}
isLoading={upcomingMovies.isLoading}
category="upcoming"
/>
</>
)}
<TrendingGrid
title="Upcoming"
movieEntries={upcomingMovieEntries}
tvEntries={[]}
isLoading={upcomingMovies.isLoading}
category="upcoming"
/>
</div>
);
}
+48 -22
View File
@@ -18,13 +18,15 @@ type SortDir = 'asc' | 'desc';
interface Filters {
genre: string;
ratingMin: string;
ratingMax: string;
tmdbRatingMin: string;
tmdbRatingMax: string;
userRatingMin: string;
userRatingMax: string;
yearMin: string;
yearMax: string;
}
const defaultFilters: Filters = { genre: '', ratingMin: '', ratingMax: '', yearMin: '', yearMax: '' };
const defaultFilters: Filters = { genre: '', tmdbRatingMin: '', tmdbRatingMax: '', userRatingMin: '', userRatingMax: '', yearMin: '', yearMax: '' };
const sortLabels: Record<SortField, string> = {
date_last_seen: 'Last Watched',
@@ -84,7 +86,7 @@ export function LibraryPage() {
const ratingMin = searchParams.get('ratingMin') || '';
const ratingMax = searchParams.get('ratingMax') || '';
if (genre || ratingMin || ratingMax) {
const newFilters = { ...defaultFilters, genre, ratingMin, ratingMax };
const newFilters = { ...defaultFilters, genre, userRatingMin: ratingMin, userRatingMax: ratingMax };
setFilters(newFilters);
setDebouncedFilters(newFilters);
// Clear URL params after applying
@@ -116,7 +118,7 @@ export function LibraryPage() {
return Array.from(set).sort();
}, [allEntries]);
const hasActiveFilters = filters.genre || filters.ratingMin || filters.ratingMax || filters.yearMin || filters.yearMax;
const hasActiveFilters = filters.genre || filters.tmdbRatingMin || filters.tmdbRatingMax || filters.userRatingMin || filters.userRatingMax || filters.yearMin || filters.yearMax;
const baseEntries = useMemo(() => {
switch (activeTab) {
@@ -144,12 +146,20 @@ export function LibraryPage() {
if (debouncedFilters.genre) {
result = result.filter((e) => e.genres?.some((g) => g.name === debouncedFilters.genre));
}
if (debouncedFilters.ratingMin) {
const min = parseFloat(debouncedFilters.ratingMin);
if (debouncedFilters.tmdbRatingMin) {
const min = parseFloat(debouncedFilters.tmdbRatingMin);
result = result.filter((e) => (e.entryRatings?.tmdb_rating ?? 0) >= min);
}
if (debouncedFilters.tmdbRatingMax) {
const max = parseFloat(debouncedFilters.tmdbRatingMax);
result = result.filter((e) => (e.entryRatings?.tmdb_rating ?? 0) <= max);
}
if (debouncedFilters.userRatingMin) {
const min = parseFloat(debouncedFilters.userRatingMin);
result = result.filter((e) => (e.entryRatings?.user_rating ?? 0) >= min);
}
if (debouncedFilters.ratingMax) {
const max = parseFloat(debouncedFilters.ratingMax);
if (debouncedFilters.userRatingMax) {
const max = parseFloat(debouncedFilters.userRatingMax);
result = result.filter((e) => (e.entryRatings?.user_rating ?? 0) <= max);
}
if (debouncedFilters.yearMin) {
@@ -260,7 +270,7 @@ export function LibraryPage() {
</Button>
</PopoverTrigger>
<PopoverContent className="w-72 space-y-4" align="end">
<div className="space-y-2">
<div className="">
<label className="text-sm font-medium">Genre</label>
<Select value={filters.genre} onValueChange={(v) => setFilters((f) => ({ ...f, genre: v === '_all' ? '' : (v || '') }))}>
<SelectTrigger className="h-9"><SelectValue placeholder="All genres" /></SelectTrigger>
@@ -270,15 +280,23 @@ export function LibraryPage() {
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Rating Range</label>
<div className="">
<label className="text-sm font-medium">TMDB Rating</label>
<div className="flex items-center gap-2">
<Input type="number" placeholder="Min" min={0} max={10} step={0.1} value={filters.ratingMin} onChange={(e) => setFilters((f) => ({ ...f, ratingMin: e.target.value }))} className="h-9" />
<Input type="number" placeholder="Min" min={0} max={10} step={1} value={filters.tmdbRatingMin} onChange={(e) => setFilters((f) => ({ ...f, tmdbRatingMin: e.target.value }))} className="h-9" />
<span className="text-muted-foreground">–</span>
<Input type="number" placeholder="Max" min={0} max={10} step={0.1} value={filters.ratingMax} onChange={(e) => setFilters((f) => ({ ...f, ratingMax: e.target.value }))} className="h-9" />
<Input type="number" placeholder="Max" min={0} max={10} step={1} value={filters.tmdbRatingMax} onChange={(e) => setFilters((f) => ({ ...f, tmdbRatingMax: e.target.value }))} className="h-9" />
</div>
</div>
<div className="space-y-2">
<div className="">
<label className="text-sm font-medium">User Rating</label>
<div className="flex items-center gap-2">
<Input type="number" placeholder="Min" min={0} max={10} step={1} value={filters.userRatingMin} onChange={(e) => setFilters((f) => ({ ...f, userRatingMin: e.target.value }))} className="h-9" />
<span className="text-muted-foreground">–</span>
<Input type="number" placeholder="Max" min={0} max={10} step={1} value={filters.userRatingMax} onChange={(e) => setFilters((f) => ({ ...f, userRatingMax: e.target.value }))} className="h-9" />
</div>
</div>
<div className="">
<label className="text-sm font-medium">Year Range</label>
<div className="flex items-center gap-2">
<Input type="number" placeholder="From" min={1950} max={2100} value={filters.yearMin} onChange={(e) => setFilters((f) => ({ ...f, yearMin: e.target.value }))} className="h-9" />
@@ -371,22 +389,30 @@ export function LibraryPage() {
</Button>
</PopoverTrigger>
<PopoverContent className="w-72 space-y-4" align="end">
<div className="space-y-2">
<div className="space-y-2 mb-0">
<label className="text-sm font-medium">Genre</label>
<Select value={filters.genre} onValueChange={(v) => setFilters((f) => ({ ...f, genre: v === '_all' ? '' : (v || '') }))}>
<SelectTrigger className="h-9"><SelectValue placeholder="All genres" /></SelectTrigger>
<Select value={filters.genre} onValueChange={(v) => setFilters((f) => ({ ...f, genre: v === '_all' ? '' : (v || '') }))}>
<SelectTrigger className="h-9 w-full"><SelectValue placeholder="All genres" /></SelectTrigger>
<SelectContent>
<SelectItem value="_all">All genres</SelectItem>
{allGenres.map((g) => <SelectItem key={g} value={g}>{g}</SelectItem>)}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Rating Range</label>
<div className="space-y-2 mb-0">
<label className="text-sm font-medium">TMDB Rating</label>
<div className="flex items-center gap-2">
<Input type="number" placeholder="Min" min={0} max={10} step={0.1} value={filters.ratingMin} onChange={(e) => setFilters((f) => ({ ...f, ratingMin: e.target.value }))} className="h-9" />
<Input type="number" placeholder="Min" min={0} max={10} step={1} value={filters.tmdbRatingMin} onChange={(e) => setFilters((f) => ({ ...f, tmdbRatingMin: e.target.value }))} className="h-9" />
<span className="text-muted-foreground">–</span>
<Input type="number" placeholder="Max" min={0} max={10} step={0.1} value={filters.ratingMax} onChange={(e) => setFilters((f) => ({ ...f, ratingMax: e.target.value }))} className="h-9" />
<Input type="number" placeholder="Max" min={0} max={10} step={1} value={filters.tmdbRatingMax} onChange={(e) => setFilters((f) => ({ ...f, tmdbRatingMax: e.target.value }))} className="h-9" />
</div>
</div>
<div className="space-y-2 mb-0">
<label className="text-sm font-medium">User Rating</label>
<div className="flex items-center gap-2">
<Input type="number" placeholder="Min" min={0} max={10} step={1} value={filters.userRatingMin} onChange={(e) => setFilters((f) => ({ ...f, userRatingMin: e.target.value }))} className="h-9" />
<span className="text-muted-foreground">–</span>
<Input type="number" placeholder="Max" min={0} max={10} step={1} value={filters.userRatingMax} onChange={(e) => setFilters((f) => ({ ...f, userRatingMax: e.target.value }))} className="h-9" />
</div>
</div>
<div className="space-y-2">
+71 -15
View File
@@ -1,6 +1,7 @@
import { useState, useMemo } from 'react';
import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import { useLibrary } from '@/hooks/useEntries';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import { useDebounce } from '@/hooks/useDebounce';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
@@ -8,13 +9,38 @@ import { Search } from 'lucide-react';
import { getMediaUrl } from '@/lib/api';
import type { Media } from '@/types';
const PAGE_SIZE = 36;
export function MediaPage() {
const { isLoading } = useLibrary();
const [search, setSearch] = useState('');
const debouncedSearch = useDebounce(search, 300);
const [mediaType, setMediaType] = useState<'all' | 'poster' | 'backdrop' | 'logo'>('all');
const [customFilter, setCustomFilter] = useState<'all' | 'custom' | 'official'>('custom');
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const entries = useLibraryEntries();
const observerRef = useRef<IntersectionObserver | null>(null);
const lastItemRef = useCallback(
(node: HTMLDivElement | null) => {
if (isLoading) return;
if (observerRef.current) observerRef.current.disconnect();
observerRef.current = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && hasMore) {
setVisibleCount((c) => c + PAGE_SIZE);
}
});
if (node) observerRef.current.observe(node);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[isLoading]
);
useEffect(() => {
return () => observerRef.current?.disconnect();
}, []);
const allMedias = useMemo(() => {
const medias: (Media & { entryTitle: string })[] = [];
entries.forEach((entry) => {
@@ -32,19 +58,58 @@ export function MediaPage() {
result = result.filter((m) => m.type === mediaType);
}
if (search) {
const q = search.toLowerCase();
if (customFilter === 'custom') {
result = result.filter((m) => m.is_custom);
} else if (customFilter === 'official') {
result = result.filter((m) => !m.is_custom);
}
if (debouncedSearch) {
const q = debouncedSearch.toLowerCase();
result = result.filter((m) => m.entryTitle.toLowerCase().includes(q));
}
return result;
}, [allMedias, mediaType, search]);
}, [allMedias, mediaType, customFilter, debouncedSearch]);
useEffect(() => {
setVisibleCount(PAGE_SIZE);
}, [mediaType, customFilter, debouncedSearch]);
const paginatedMedia = useMemo(
() => filtered.slice(0, visibleCount),
[filtered, visibleCount]
);
const hasMore = visibleCount < filtered.length;
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">Media</h1>
<div className="flex flex-wrap items-center gap-3">
<div className="relative flex-1 max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search by title..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
<div className="flex-1" />
<Tabs
value={customFilter}
onValueChange={(v) => setCustomFilter(v as typeof customFilter)}
>
<TabsList>
<TabsTrigger value="all">All</TabsTrigger>
<TabsTrigger value="custom">Custom</TabsTrigger>
<TabsTrigger value="official">Official</TabsTrigger>
</TabsList>
</Tabs>
<Tabs
value={mediaType}
onValueChange={(v) => setMediaType(v as typeof mediaType)}
@@ -56,16 +121,6 @@ export function MediaPage() {
<TabsTrigger value="logo">Logos</TabsTrigger>
</TabsList>
</Tabs>
<div className="relative flex-1 max-w-xs">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search by title..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-10"
/>
</div>
</div>
{isLoading ? (
@@ -93,9 +148,10 @@ export function MediaPage() {
: 'grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6'
}`}
>
{filtered.map((media) => (
{paginatedMedia.map((media, index) => (
<div
key={media.id}
ref={index === paginatedMedia.length - 1 ? lastItemRef : undefined}
className="group relative overflow-hidden rounded-lg bg-muted"
>
<img
+31 -13
View File
@@ -25,11 +25,11 @@ export function PersonDetailsPage() {
if (isLoading || !person) {
return (
<div className="space-y-6">
<div className="flex gap-6">
<Skeleton className="h-48 w-48 rounded-full" />
<div className="flex-1 space-y-3">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-4 w-32" />
<div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start sm:gap-6">
<Skeleton className="h-32 w-32 rounded-full sm:h-48 sm:w-48" />
<div className="flex-1 space-y-3 w-full">
<Skeleton className="h-8 w-48 mx-auto sm:mx-0" />
<Skeleton className="h-4 w-32 mx-auto sm:mx-0" />
<Skeleton className="h-20 w-full" />
</div>
</div>
@@ -39,16 +39,16 @@ export function PersonDetailsPage() {
return (
<div className="space-y-8">
<div className="flex gap-8">
<Avatar className="h-48 w-48 shrink-0">
<div className="flex flex-col items-center gap-4 sm:flex-row sm:items-start sm:gap-8">
<Avatar className="h-32 w-32 shrink-0 sm:h-48 sm:w-48">
<AvatarImage src={getProfileUrl(person.profile_path)} alt={person.name} />
<AvatarFallback className="text-3xl">
<AvatarFallback className="text-2xl sm:text-3xl">
{person.name.split(' ').map((n: string) => n[0]).join('')}
</AvatarFallback>
</Avatar>
<div className="space-y-3">
<h1 className="text-3xl font-bold">{person.name}</h1>
<div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
<div className="space-y-2 text-center sm:text-left sm:space-y-3">
<h1 className="text-2xl font-bold sm:text-3xl">{person.name}</h1>
<div className="flex flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground sm:justify-start sm:gap-3">
{person.known_for_department && <span>{person.known_for_department}</span>}
{person.birthday && (<><span>•</span><span>Born: {formatDate(person.birthday)}</span></>)}
{person.deathday && (<><span>•</span><span>Died: {formatDate(person.deathday)}</span></>)}
@@ -85,7 +85,7 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
const [libraryPage, setLibraryPage] = useState(0);
const [otherPage, setOtherPage] = useState(0);
const PAGE_SIZE = 6; // 6 cols × 1 row
const GRID = 'grid grid-cols-3 gap-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6';
const GRID = 'grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6';
if (tmdbLoading || !libraryLoaded) {
return (
@@ -121,7 +121,25 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
// Sort by popularity descending
const sorted = [...dedupedCredits].sort((a, b) => (b.popularity ?? 0) - (a.popularity ?? 0));
const libraryCredits = sorted.filter((c) => tmdbIdToLibraryEntry.has(c.id));
const otherCredits = sorted.filter((c) => !tmdbIdToLibraryEntry.has(c.id));
// "Not in library": sort by release date (new→old), push "self" roles to the end
const isSelfRole = (character?: string) => {
if (!character) return false;
const lower = character.toLowerCase().trim();
return lower === 'self' || lower.startsWith('self -') || lower.startsWith('self (') || lower === 'themselves' || lower === 'himself' || lower === 'herself';
};
const otherCreditsSorted = sorted
.filter((c) => !tmdbIdToLibraryEntry.has(c.id))
.sort((a, b) => {
const aSelf = isSelfRole(a.character) ? 1 : 0;
const bSelf = isSelfRole(b.character) ? 1 : 0;
if (aSelf !== bSelf) return aSelf - bSelf;
// Both same self status → sort by date descending (new first)
const dateA = new Date(a.release_date || a.first_air_date || '1900').getTime();
const dateB = new Date(b.release_date || b.first_air_date || '1900').getTime();
return dateB - dateA;
});
const otherCredits = otherCreditsSorted;
if (sorted.length === 0) {
return (
+120
View File
@@ -0,0 +1,120 @@
import { useState, useEffect, useRef } from 'react';
import { useSearchParams, Link } from 'react-router-dom';
import { useTmdbSearch, useTmdbSearchPeople } from '@/hooks/useTmdb';
import { useLibrary } from '@/hooks/useEntries';
import { Input } from '@/components/ui/input';
import { Search } from 'lucide-react';
import { EntryCard } from '@/components/entries/EntryCard';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { getTmdbImageUrl } from '@/lib/api';
export function SearchPage() {
const [searchParams, setSearchParams] = useSearchParams();
const initialQuery = searchParams.get('q') || '';
const [searchInput, setSearchInput] = useState(initialQuery);
const [debouncedQuery, setDebouncedQuery] = useState(initialQuery);
const debounceRef = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => {
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => {
setDebouncedQuery(searchInput);
}, 400);
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [searchInput]);
// Sync debounced query to URL
useEffect(() => {
if (debouncedQuery) {
setSearchParams({ q: debouncedQuery }, { replace: true });
} else {
setSearchParams({}, { replace: true });
}
}, [debouncedQuery, setSearchParams]);
useLibrary();
const searchResults = useTmdbSearch(debouncedQuery);
const peopleResults = useTmdbSearchPeople(debouncedQuery);
const searchEntries = searchResults.data?.pages.flatMap((p) => p.results) ?? [];
const searchPeople = peopleResults.data?.pages.flatMap((p) => p.results) ?? [];
const isSearching = debouncedQuery.length > 0;
return (
<div className="space-y-6 animate-page-enter">
{/* Search */}
<div className="relative max-w-md">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
placeholder="Search movies, TV shows & people..."
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
className="pl-10"
autoFocus
/>
</div>
{isSearching ? (
<div className="space-y-6">
{/* People results */}
{searchPeople.length > 0 && (
<div className="space-y-3">
<h2 className="text-lg font-semibold">People</h2>
<div className="flex flex-wrap gap-3">
{searchPeople.slice(0, 10).map((person) => (
<Link
key={person.id}
to={`/people/tmdb/${person.id}`}
className="flex items-center gap-2 rounded-full bg-muted px-3 py-1.5 transition-colors hover:bg-accent"
>
<Avatar className="h-7 w-7">
<AvatarImage
src={person.profile_path ? getTmdbImageUrl(person.profile_path, 'w92') : undefined}
alt={person.name}
/>
<AvatarFallback className="text-xs">
{person.name.split(' ').map((n) => n[0]).join('').slice(0, 2)}
</AvatarFallback>
</Avatar>
<span className="text-sm font-medium">{person.name}</span>
{person.known_for_department && (
<span className="text-xs text-muted-foreground">{person.known_for_department}</span>
)}
</Link>
))}
</div>
</div>
)}
{/* Entry results */}
<h2 className="text-xl font-semibold">
Search Results for &ldquo;{debouncedQuery}&rdquo;
</h2>
{searchEntries.length === 0 && !searchResults.isLoading ? (
<p className="text-muted-foreground">No results found.</p>
) : (
<div className="grid grid-cols-2 gap-3 sm:gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-7">
{searchEntries.map((entry, index) => (
<div
key={entry.id}
className="animate-card-enter"
style={{ animationDelay: `${Math.min(index * 30, 300)}ms` }}
>
<EntryCard tmdbEntry={entry} showTypeBadge />
</div>
))}
</div>
)}
</div>
) : (
<div className="flex h-40 items-center justify-center text-muted-foreground">
Start typing to search...
</div>
)}
</div>
);
}
+52 -6
View File
@@ -1,17 +1,20 @@
import { useState, useMemo, useCallback } from 'react';
import { useState, useMemo, useCallback, useEffect } from 'react';
import { useLibrary } from '@/hooks/useEntries';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import { useDebounce } from '@/hooks/useDebounce';
import { EntryLibraryGrid } from '@/components/entries/EntryLibraryGrid';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Search, SlidersHorizontal, ArrowUpDown } from 'lucide-react';
import type { Entry } from '@/types';
type SortField = 'createdAt' | 'date_last_seen' | 'title' | 'release_date' | 'rating';
type SortDir = 'asc' | 'desc';
type TypeFilter = 'all' | 'movies' | 'tv';
interface Filters {
genre: string;
@@ -56,12 +59,17 @@ function sortEntries(entries: Entry[], field: SortField, dir: SortDir): Entry[]
});
}
const PAGE_SIZE = 28;
export function WatchlistPage() {
const { isLoading } = useLibrary();
const [search, setSearch] = useState('');
const debouncedSearch = useDebounce(search, 300);
const [sortField, setSortField] = useState<SortField>('createdAt');
const [sortDir, setSortDir] = useState<SortDir>('desc');
const [filters, setFilters] = useState<Filters>(defaultFilters);
const [typeFilter, setTypeFilter] = useState<TypeFilter>('all');
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const allEntries = useLibraryEntries();
const watchlist = useMemo(() => allEntries.filter((e) => e.watchlist), [allEntries]);
@@ -76,8 +84,14 @@ export function WatchlistPage() {
const filtered = useMemo(() => {
let result = watchlist;
if (search) {
const q = search.toLowerCase();
if (typeFilter === 'movies') {
result = result.filter((e) => !e.is_tvseries);
} else if (typeFilter === 'tv') {
result = result.filter((e) => e.is_tvseries);
}
if (debouncedSearch) {
const q = debouncedSearch.toLowerCase();
result = result.filter((e) => e.title.toLowerCase().includes(q));
}
@@ -102,7 +116,19 @@ export function WatchlistPage() {
}
return sortEntries(result, sortField, sortDir);
}, [watchlist, search, filters, sortField, sortDir]);
}, [watchlist, debouncedSearch, filters, sortField, sortDir, typeFilter]);
// Reset visible count when filters change
useEffect(() => {
setVisibleCount(PAGE_SIZE);
}, [debouncedSearch, filters, sortField, sortDir, typeFilter]);
const paginatedEntries = useMemo(
() => filtered.slice(0, visibleCount),
[filtered, visibleCount]
);
const hasMore = visibleCount < filtered.length;
const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []);
const clearFilters = useCallback(() => setFilters(defaultFilters), []);
@@ -201,6 +227,17 @@ export function WatchlistPage() {
</PopoverContent>
</Popover>
</div>
{/* Row 2: type filter tabs */}
<div className="overflow-x-auto pb-1">
<Tabs value={typeFilter} onValueChange={(v) => setTypeFilter(v as TypeFilter)}>
<TabsList className="w-max">
<TabsTrigger value="all">All</TabsTrigger>
<TabsTrigger value="movies">Movies</TabsTrigger>
<TabsTrigger value="tv">TV Series</TabsTrigger>
</TabsList>
</Tabs>
</div>
</div>
{/* ── Desktop controls (≥ md) ── */}
@@ -284,7 +321,7 @@ export function WatchlistPage() {
<div className="flex items-center gap-2">
<Input type="number" placeholder="From" min={1950} max={2100} value={filters.yearMin} onChange={(e) => setFilters((f) => ({ ...f, yearMin: e.target.value }))} className="h-9" />
<span className="text-muted-foreground">–</span>
<Input type="number" placeholder="To" min={1950} max={2100} value={filters.yearMax} onChange={(e) => setFilters((f) => ({ ...f, yearMax: e.target.value }))}
<Input type="number" placeholder="To" min={1950} max={2100} value={filters.yearMax} onChange={(e) => setFilters((f) => ({ ...f, ratingMax: e.target.value }))}
className="h-9"
/>
</div>
@@ -296,9 +333,18 @@ export function WatchlistPage() {
)}
</PopoverContent>
</Popover>
{/* Type filter */}
<Tabs value={typeFilter} onValueChange={(v) => setTypeFilter(v as TypeFilter)}>
<TabsList>
<TabsTrigger value="all">All</TabsTrigger>
<TabsTrigger value="movies">Movies</TabsTrigger>
<TabsTrigger value="tv">TV Series</TabsTrigger>
</TabsList>
</Tabs>
</div>
<EntryLibraryGrid entries={filtered} isLoading={isLoading} />
<EntryLibraryGrid entries={paginatedEntries} isLoading={isLoading} hasMore={hasMore} onLoadMore={loadMore} />
</div>
);
}
+11
View File
@@ -77,6 +77,9 @@ const SettingsPage = lazy(() =>
const DiscoverPage = lazy(() =>
import('@/pages/DiscoverPage').then((m) => ({ default: m.DiscoverPage }))
);
const SearchPage = lazy(() =>
import('@/pages/SearchPage').then((m) => ({ default: m.SearchPage }))
);
function SuspensePage({ children, fallback }: { children: ReactNode; fallback?: ReactNode }) {
return <Suspense fallback={fallback ?? <HomeSkeleton />}>{children}</Suspense>;
@@ -94,6 +97,14 @@ export const router = createBrowserRouter([
</SuspensePage>
),
},
{
path: '/search',
element: (
<SuspensePage fallback={<HomeSkeleton />}>
<SearchPage />
</SuspensePage>
),
},
{
path: '/dashboard',
element: (