feat(people): unify person detail page for DB and TMDB sources

- Merge PersonDetailsPage and PersonTmdbRedirectPage into one component
- /people/:id fetches from local DB with favorite toggle
- /people/tmdb/:tmdbId fetches from TMDB with "Add to Library" button
- Add TMDB external link in person metadata
- Fix CastList links for TMDB preview cast (use /people/tmdb/:tmdbId)
- Replace 11MB getAll() with server-side paginated infinite scroll
- Add useLocalPeopleInfinite hook and PaginatedPeopleResponse type
This commit is contained in:
Mohammed Abad committed 2026-04-27 13:29:30 +01:00
1 parent 6d676d803c
commit db6da6782f
6 files changed
+231 -59

No files matched your search

+12
View File
@@ -35,9 +35,21 @@ export interface TmdbPersonPreview {
filmography: TmdbFilmographyResponse;
}
export interface PaginatedPeopleResponse {
data: People[];
total: number;
page: number;
totalPages: number;
}
export const peopleApi = {
getAll: () => api.get<People[]>('/people').then((r) => r.data),
getAllPaginated: (page: number, limit: number, search?: string) =>
api
.get<PaginatedPeopleResponse>('/people', { params: { page, limit, ...(search ? { search } : {}) } })
.then((r) => r.data),
getById: (id: number) =>
api.get<People>(`/people/${id}`).then((r) => r.data),
@@ -33,9 +33,14 @@ function CastCard({ credit }: { credit: Credit }) {
? getProfileUrl(credit.people.profile_path)
: undefined;
// For local DB credits, link to /people/:id. For TMDB preview credits (no entry_id), link via tmdb_id.
const personLink = credit.entry_id
? `/people/${credit.people_id}`
: `/people/tmdb/${credit.people?.tmdb_id ?? credit.people_id}`;
return (
<Link
to={`/people/${credit.people_id}`}
to={personLink}
className="flex w-28 shrink-0 flex-col items-center gap-2 text-center"
>
<Avatar className="h-20 w-20">
+15 -1
View File
@@ -1,4 +1,4 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from '@tanstack/react-query';
import { toast } from 'sonner';
import { peopleApi } from '@/api/people';
@@ -73,3 +73,17 @@ export function useSearchLocalPeople(query: string) {
enabled: query.length > 0,
});
}
const LOCAL_PEOPLE_PAGE_SIZE = 48;
export function useLocalPeopleInfinite(search: string, enabled: boolean) {
return useInfiniteQuery({
queryKey: ['people', 'paginated', search],
queryFn: ({ pageParam = 1 }) =>
peopleApi.getAllPaginated(pageParam, LOCAL_PEOPLE_PAGE_SIZE, search || undefined),
getNextPageParam: (lastPage) =>
lastPage.page < lastPage.totalPages ? lastPage.page + 1 : undefined,
initialPageParam: 1,
enabled,
});
}
+21 -27
View File
@@ -1,7 +1,7 @@
import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { usePopularPeople, useTmdbSearchPeople } from '@/hooks/useTmdb';
import { useSearchLocalPeople } from '@/hooks/usePeople';
import { useLocalPeopleInfinite } from '@/hooks/usePeople';
import { Input } from '@/components/ui/input';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
@@ -12,14 +12,12 @@ import { Search, Heart } from 'lucide-react';
import { getProfileUrl } from '@/lib/media-utils';
type PeopleFilter = 'all' | 'favorite';
const LOCAL_PAGE_SIZE = 48;
export function PeoplePage() {
const [search, setSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const [filter, setFilter] = useState<PeopleFilter>('all');
const [localOnly, setLocalOnly] = useState(false);
const [localVisibleCount, setLocalVisibleCount] = useState(LOCAL_PAGE_SIZE);
// Debounce search input
useEffect(() => {
@@ -27,46 +25,40 @@ export function PeoplePage() {
return () => clearTimeout(timer);
}, [search]);
// Reset visible count when filter/search changes
useEffect(() => {
setLocalVisibleCount(LOCAL_PAGE_SIZE);
}, [debouncedSearch, filter, localOnly]);
const isSearching = debouncedSearch.length > 0;
const popularQuery = usePopularPeople();
const tmdbSearchQuery = useTmdbSearchPeople(localOnly ? '' : debouncedSearch);
const { data: localSearchResults = [], isLoading: localSearchLoading } = useSearchLocalPeople(
localOnly ? debouncedSearch : ''
// Paginated local people (handles both search and browse)
const localPeopleQuery = useLocalPeopleInfinite(
localOnly ? debouncedSearch : '',
localOnly,
);
// For TMDB mode, use infinite scroll queries
const activeQuery = isSearching && !localOnly ? tmdbSearchQuery : !localOnly ? popularQuery : null;
const tmdbPeople = activeQuery?.data?.pages.flatMap((p) => p.results) ?? [];
// For local mode with no search, fetch all local people
const { data: allLocalPeople = [], isLoading: allLocalLoading } = useSearchLocalPeople(
localOnly && !isSearching ? '*' : ''
// Flatten paginated local results
const allLocalPeople = useMemo(
() => localPeopleQuery.data?.pages.flatMap((p) => p.data) ?? [],
[localPeopleQuery.data],
);
// Determine displayed people
// Apply client-side favorite filter
const filteredLocalPeople = useMemo(() => {
if (!localOnly) return [];
const people = isSearching ? localSearchResults : allLocalPeople;
if (filter === 'favorite') {
return people.filter((p: any) => p.favorite);
return allLocalPeople.filter((p: any) => p.favorite);
}
return people;
}, [localOnly, isSearching, localSearchResults, allLocalPeople, filter]);
return allLocalPeople;
}, [localOnly, allLocalPeople, filter]);
const displayPeople = useMemo(() => {
if (localOnly) {
return filteredLocalPeople.slice(0, localVisibleCount);
}
if (localOnly) return filteredLocalPeople;
return tmdbPeople;
}, [localOnly, filteredLocalPeople, localVisibleCount, tmdbPeople]);
const hasMoreLocal = localOnly && localVisibleCount < filteredLocalPeople.length;
}, [localOnly, filteredLocalPeople, tmdbPeople]);
const observerRef = useRef<IntersectionObserver | null>(null);
const lastRef = useCallback(
@@ -76,14 +68,16 @@ export function PeoplePage() {
observerRef.current = new IntersectionObserver((entries) => {
if (!entries[0].isIntersecting) return;
if (localOnly) {
if (hasMoreLocal) setLocalVisibleCount((c) => c + LOCAL_PAGE_SIZE);
if (localPeopleQuery.hasNextPage && !localPeopleQuery.isFetchingNextPage) {
localPeopleQuery.fetchNextPage();
}
} else if (activeQuery && !activeQuery.isFetchingNextPage && activeQuery.hasNextPage) {
activeQuery.fetchNextPage();
}
});
observerRef.current.observe(node);
},
[localOnly, hasMoreLocal, activeQuery?.isFetchingNextPage, activeQuery?.hasNextPage, activeQuery?.fetchNextPage]
[localOnly, localPeopleQuery.hasNextPage, localPeopleQuery.isFetchingNextPage, localPeopleQuery.fetchNextPage, activeQuery?.isFetchingNextPage, activeQuery?.hasNextPage, activeQuery?.fetchNextPage]
);
useEffect(() => {
@@ -91,7 +85,7 @@ export function PeoplePage() {
}, []);
const isLoading = localOnly
? (isSearching ? localSearchLoading : allLocalLoading)
? localPeopleQuery.isLoading
: activeQuery?.isLoading;
return (
+176 -24
View File
@@ -1,6 +1,12 @@
import { useParams, useNavigate } from 'react-router-dom';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { useState } from 'react';
import { usePerson, usePersonTmdbFilmography, useUpdatePerson } from '@/hooks/usePeople';
import {
usePerson,
usePersonTmdbFilmography,
useUpdatePerson,
useTmdbPersonPreview,
useFetchPersonByTmdbId,
} from '@/hooks/usePeople';
import { useLibrary } from '@/hooks/useEntries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { Skeleton } from '@/components/ui/skeleton';
@@ -9,13 +15,27 @@ import { Separator } from '@/components/ui/separator';
import { Button } from '@/components/ui/button';
import { EntryCard } from '@/components/entries/EntryCard';
import { getProfileUrl, formatDate } from '@/lib/media-utils';
import { ChevronLeft, ChevronRight, Heart } from 'lucide-react';
import { ChevronLeft, ChevronRight, Heart, Plus, Loader2, ExternalLink } from 'lucide-react';
import type { TmdbEntry } from '@/types';
import type { TmdbFilmographyItem } from '@/api/people';
const TMDB_IMG = 'https://image.tmdb.org/t/p';
export function PersonDetailsPage() {
const { id } = useParams<{ id: string }>();
const personId = parseInt(id!, 10);
const { id, tmdbId } = useParams<{ id?: string; tmdbId?: string }>();
const location = useLocation();
const isTmdbMode = location.pathname.startsWith('/people/tmdb/');
if (isTmdbMode && tmdbId) {
return <TmdbPersonView tmdbId={parseInt(tmdbId, 10)} />;
}
return <LocalPersonView personId={parseInt(id!, 10)} />;
}
/* ─── Local DB person ─── */
function LocalPersonView({ personId }: { personId: number }) {
const navigate = useNavigate();
const { data: person, isLoading, isError } = usePerson(personId);
const { data: tmdbFilmography, isLoading: tmdbLoading } = usePersonTmdbFilmography(personId);
@@ -39,22 +59,11 @@ export function PersonDetailsPage() {
}
if (isLoading || !person) {
return (
<div className="space-y-6">
<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>
</div>
);
return <PersonSkeleton />;
}
return (
<div className="space-y-8">
<div className="space-y-8 animate-page-enter">
<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} />
@@ -75,12 +84,13 @@ export function PersonDetailsPage() {
<Heart className={`h-5 w-5 ${person.favorite ? 'fill-red-500 text-red-500' : 'text-muted-foreground'}`} />
</Button>
</div>
<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></>)}
{person.place_of_birth && (<><span>•</span><span>{person.place_of_birth}</span></>)}
</div>
<PersonMeta
known_for_department={person.known_for_department}
birthday={person.birthday}
deathday={person.deathday}
place_of_birth={person.place_of_birth}
tmdb_id={person.tmdb_id}
/>
{person.biography && (
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl line-clamp-6">
{person.biography}
@@ -101,6 +111,148 @@ export function PersonDetailsPage() {
);
}
/* ─── TMDB person (not in library) ─── */
function TmdbPersonView({ tmdbId }: { tmdbId: number }) {
const navigate = useNavigate();
const { data: preview, isLoading, isError } = useTmdbPersonPreview(tmdbId);
const fetchPerson = useFetchPersonByTmdbId();
useLibrary();
const libraryMap = useLibraryStore((s) => s.entries);
const libraryLoaded = useLibraryStore((s) => s.isLoaded);
if (isError) {
return (
<div className="flex flex-col items-center justify-center gap-3 py-20">
<p className="text-lg font-semibold">Person not found</p>
<p className="text-sm text-muted-foreground">
Could not load person data from TMDB.
</p>
<Button variant="outline" onClick={() => navigate(-1)}>Go back</Button>
</div>
);
}
if (isLoading || !preview) {
return <PersonSkeleton />;
}
const profileUrl = preview.profile_path
? `${TMDB_IMG}/w300${preview.profile_path}`
: undefined;
const handleAddToLibrary = () => {
fetchPerson.mutate(tmdbId, {
onSuccess: (person) => {
navigate(`/people/${person.id}`, { replace: true });
},
});
};
return (
<div className="space-y-8 animate-page-enter">
<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={profileUrl} alt={preview.name} />
<AvatarFallback className="text-2xl sm:text-3xl">
{preview.name.split(' ').map((n: string) => n[0]).join('')}
</AvatarFallback>
</Avatar>
<div className="space-y-2 text-center sm:text-left sm:space-y-3">
<div className="flex items-center gap-3 justify-center sm:justify-start">
<h1 className="text-2xl font-bold sm:text-3xl">{preview.name}</h1>
<Button onClick={handleAddToLibrary} disabled={fetchPerson.isPending} size="sm">
{fetchPerson.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
{fetchPerson.isPending ? 'Adding...' : 'Add to Library'}
</Button>
</div>
<PersonMeta
known_for_department={preview.known_for_department}
birthday={preview.birthday}
deathday={preview.deathday}
place_of_birth={preview.place_of_birth}
tmdb_id={preview.tmdb_id}
/>
{preview.biography && (
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl line-clamp-6">
{preview.biography}
</p>
)}
</div>
</div>
<Separator />
<FilmographySection
libraryMap={libraryMap}
libraryLoaded={libraryLoaded}
tmdbFilmography={preview.filmography}
tmdbLoading={false}
/>
</div>
);
}
/* ─── Shared components ─── */
function PersonMeta({
known_for_department,
birthday,
deathday,
place_of_birth,
tmdb_id,
}: {
known_for_department?: string | null;
birthday?: string | null;
deathday?: string | null;
place_of_birth?: string | null;
tmdb_id?: number | null;
}) {
return (
<div className="flex flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground sm:justify-start sm:gap-3">
{known_for_department && <span>{known_for_department}</span>}
{birthday && (<><span>•</span><span>Born: {formatDate(birthday)}</span></>)}
{deathday && (<><span>•</span><span>Died: {formatDate(deathday)}</span></>)}
{place_of_birth && (<><span>•</span><span>{place_of_birth}</span></>)}
{tmdb_id && (
<>
<span>•</span>
<a
href={`https://www.themoviedb.org/person/${tmdb_id}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors"
>
<ExternalLink className="h-3 w-3" />
TMDB
</a>
</>
)}
</div>
);
}
function PersonSkeleton() {
return (
<div className="space-y-6">
<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>
</div>
);
}
/* ─── Filmography ─── */
interface FilmographySectionProps {
libraryMap: Map<number, import('@/types').Entry>;
libraryLoaded: boolean;
+1 -6
View File
@@ -71,11 +71,6 @@ const PersonDetailsPage = lazy(() =>
default: m.PersonDetailsPage,
}))
);
const PersonTmdbRedirectPage = lazy(() =>
import('@/pages/PersonTmdbRedirectPage').then((m) => ({
default: m.PersonTmdbRedirectPage,
}))
);
const SettingsPage = lazy(() =>
import('@/pages/SettingsPage').then((m) => ({ default: m.SettingsPage }))
);
@@ -218,7 +213,7 @@ export const router = createBrowserRouter([
path: '/people/tmdb/:tmdbId',
element: (
<SuspensePage fallback={<PersonDetailsSkeleton />}>
<PersonTmdbRedirectPage />
<PersonDetailsPage />
</SuspensePage>
),
},