Normalize to double quotes across all files with Prettier

This commit is contained in:
X4Lo committed 2026-06-21 22:28:08 +01:00
1 parent 73bff72cec
commit a5659cf4c8
190 files changed
+9523 -8859

No files matched your search

+143 -64
View File
@@ -1,31 +1,56 @@
import { useState, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { format, startOfMonth, endOfMonth, eachDayOfInterval, getDay, addMonths, subMonths, isSameDay } from 'date-fns';
import { ChevronLeft, ChevronRight, LayoutGrid, List } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { useEpisodesByMonth } from '@/hooks/useEpisodes';
import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from '@/components/ui/tooltip';
import { getTmdbPosterUrl } from '@/lib/media-utils';
import type { Episode } from '@/types';
import { useState, useMemo } from "react";
import { Link } from "react-router-dom";
import {
format,
startOfMonth,
endOfMonth,
eachDayOfInterval,
getDay,
addMonths,
subMonths,
isSameDay,
} from "date-fns";
import { ChevronLeft, ChevronRight, LayoutGrid, List } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { useEpisodesByMonth } from "@/hooks/useEpisodes";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
TooltipProvider,
} from "@/components/ui/tooltip";
import { getTmdbPosterUrl } from "@/lib/media-utils";
import type { Episode } from "@/types";
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
export function CalendarPage() {
const [currentDate, setCurrentDate] = useState(new Date());
const [viewMode, setViewMode] = useState<'grid' | 'list'>(
() => (typeof window !== 'undefined' && window.innerWidth < 640 ? 'list' : 'grid')
const [viewMode, setViewMode] = useState<"grid" | "list">(() =>
typeof window !== "undefined" && window.innerWidth < 640 ? "list" : "grid",
);
const [selectedDay, setSelectedDay] = useState<{ date: Date; episodes: Episode[] } | null>(null);
const [selectedDay, setSelectedDay] = useState<{
date: Date;
episodes: Episode[];
} | null>(null);
const monthStart = startOfMonth(currentDate);
const monthEnd = endOfMonth(currentDate);
const startDateStr = format(monthStart, 'yyyy-MM-dd');
const endDateStr = format(monthEnd, 'yyyy-MM-dd');
const startDateStr = format(monthStart, "yyyy-MM-dd");
const endDateStr = format(monthEnd, "yyyy-MM-dd");
const { data: episodes = [] } = useEpisodesByMonth(startDateStr, endDateStr);
const days = useMemo(() => eachDayOfInterval({ start: monthStart, end: monthEnd }), [monthStart, monthEnd]);
const days = useMemo(
() => eachDayOfInterval({ start: monthStart, end: monthEnd }),
[monthStart, monthEnd],
);
const startDayOfWeek = getDay(monthStart);
// Group episodes by date
@@ -33,7 +58,7 @@ export function CalendarPage() {
const map = new Map<string, typeof episodes>();
episodes.forEach((ep) => {
if (!ep.air_date) return;
const key = format(new Date(ep.air_date), 'yyyy-MM-dd');
const key = format(new Date(ep.air_date), "yyyy-MM-dd");
const existing = map.get(key) || [];
existing.push(ep);
map.set(key, existing);
@@ -54,7 +79,7 @@ export function CalendarPage() {
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="min-w-35 text-center font-medium">
{format(currentDate, 'MMMM yyyy')}
{format(currentDate, "MMMM yyyy")}
</span>
<Button
variant="outline"
@@ -67,10 +92,18 @@ export function CalendarPage() {
<Button
variant="outline"
size="icon"
onClick={() => setViewMode((v) => (v === 'grid' ? 'list' : 'grid'))}
title={viewMode === 'grid' ? 'Switch to list view' : 'Switch to grid view'}
onClick={() => setViewMode((v) => (v === "grid" ? "list" : "grid"))}
title={
viewMode === "grid"
? "Switch to list view"
: "Switch to grid view"
}
>
{viewMode === 'grid' ? <List className="h-4 w-4" /> : <LayoutGrid className="h-4 w-4" />}
{viewMode === "grid" ? (
<List className="h-4 w-4" />
) : (
<LayoutGrid className="h-4 w-4" />
)}
</Button>
</div>
</div>
@@ -84,12 +117,15 @@ export function CalendarPage() {
onClose={() => setSelectedDay(null)}
/>
)}
{viewMode === 'grid' ? (
{viewMode === "grid" ? (
<div className="flex flex-col flex-1 rounded-lg border border-border overflow-hidden min-h-0">
{/* Day headers */}
<div className="grid grid-cols-7 bg-muted/50 shrink-0">
{DAYS.map((day) => (
<div key={day} className="px-2 py-2 text-center text-xs font-medium text-muted-foreground">
<div
key={day}
className="px-2 py-2 text-center text-xs font-medium text-muted-foreground"
>
{day}
</div>
))}
@@ -99,34 +135,44 @@ export function CalendarPage() {
<div className="grid grid-cols-7 grid-rows-6 flex-1 min-h-0">
{/* Empty cells for offset */}
{Array.from({ length: startDayOfWeek }).map((_, i) => (
<div key={`empty-${i}`} className="border-t border-r border-border bg-muted/20" />
<div
key={`empty-${i}`}
className="border-t border-r border-border bg-muted/20"
/>
))}
{days.map((day) => {
const key = format(day, 'yyyy-MM-dd');
const key = format(day, "yyyy-MM-dd");
const dayEpisodes = episodesByDate.get(key) || [];
const isToday = isSameDay(day, new Date());
return (
<div
key={key}
onClick={() => dayEpisodes.length > 0 && setSelectedDay({ date: day, episodes: dayEpisodes })}
onClick={() =>
dayEpisodes.length > 0 &&
setSelectedDay({ date: day, episodes: dayEpisodes })
}
className={`border-t border-r border-border p-1 overflow-hidden flex flex-col min-h-0 ${
isToday ? 'bg-primary/5' : ''
} ${dayEpisodes.length > 0 ? 'cursor-pointer hover:bg-accent/30 transition-colors' : ''}`}
isToday ? "bg-primary/5" : ""
} ${dayEpisodes.length > 0 ? "cursor-pointer hover:bg-accent/30 transition-colors" : ""}`}
>
<span
className={`inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] mb-0.5 ${
isToday
? 'bg-primary text-primary-foreground font-bold'
: 'text-muted-foreground'
? "bg-primary text-primary-foreground font-bold"
: "text-muted-foreground"
}`}
>
{format(day, 'd')}
{format(day, "d")}
</span>
<div className="flex gap-0.5 flex-1 min-h-0 overflow-hidden items-start">
{dayEpisodes.slice(0, 3).map((ep) => (
<EpisodeCalendarItem key={ep.id} episode={ep} variant="grid" />
<EpisodeCalendarItem
key={ep.id}
episode={ep}
variant="grid"
/>
))}
{dayEpisodes.length > 3 && (
<span className="text-[9px] text-muted-foreground shrink-0 self-end pb-0.5">
@@ -143,7 +189,7 @@ export function CalendarPage() {
/* List / Agenda view */
<div className="flex flex-col flex-1 overflow-y-auto min-h-0 gap-1">
{days.map((day) => {
const key = format(day, 'yyyy-MM-dd');
const key = format(day, "yyyy-MM-dd");
const dayEpisodes = episodesByDate.get(key) || [];
const isToday = isSameDay(day, new Date());
@@ -152,34 +198,39 @@ export function CalendarPage() {
key={key}
className={`rounded-lg border ${
isToday
? 'border-primary/30 bg-primary/5'
? "border-primary/30 bg-primary/5"
: dayEpisodes.length > 0
? 'border-border'
: 'border-transparent'
? "border-border"
: "border-transparent"
}`}
>
<div
className={`flex items-center gap-3 px-3 py-2 ${
dayEpisodes.length > 0 ? 'border-b border-border/40' : ''
dayEpisodes.length > 0 ? "border-b border-border/40" : ""
}`}
>
<span
className={`inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-sm ${
isToday
? 'bg-primary text-primary-foreground font-bold'
: 'text-muted-foreground'
? "bg-primary text-primary-foreground font-bold"
: "text-muted-foreground"
}`}
>
{format(day, 'd')}
{format(day, "d")}
</span>
<span className={`text-sm ${
isToday ? 'font-medium text-foreground' : 'text-muted-foreground'
}`}>
{format(day, 'EEEE, MMM d')}
<span
className={`text-sm ${
isToday
? "font-medium text-foreground"
: "text-muted-foreground"
}`}
>
{format(day, "EEEE, MMM d")}
</span>
{dayEpisodes.length > 0 && (
<span className="ml-auto text-xs text-muted-foreground">
{dayEpisodes.length} ep{dayEpisodes.length !== 1 ? 's' : ''}
{dayEpisodes.length} ep
{dayEpisodes.length !== 1 ? "s" : ""}
</span>
)}
</div>
@@ -200,14 +251,20 @@ export function CalendarPage() {
);
}
function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode; variant?: 'grid' | 'list' | 'dialog' }) {
function EpisodeCalendarItem({
episode,
variant = "list",
}: {
episode: Episode;
variant?: "grid" | "list" | "dialog";
}) {
type EpisodeWithEntry = Episode & {
entry?: { id: number; title?: string; poster_path?: string | null };
};
const ep = episode as EpisodeWithEntry;
const entry = ep.entry;
const entryId = entry?.id;
const entryTitle = entry?.title ?? '';
const entryTitle = entry?.title ?? "";
// Hide episodes with no known entry title
if (!entryTitle) return null;
@@ -215,18 +272,17 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
const seasonId = episode.season_id;
const seasonNumber = episode.season?.season_number ?? null;
const seasonLabel = seasonNumber != null
? `S${String(seasonNumber).padStart(2, '0')}`
: '';
const episodeLabel = `E${String(episode.episode_number).padStart(2, '0')}`;
const seasonLabel =
seasonNumber != null ? `S${String(seasonNumber).padStart(2, "0")}` : "";
const episodeLabel = `E${String(episode.episode_number).padStart(2, "0")}`;
const thumbSrc = entry?.poster_path
? getTmdbPosterUrl(entry.poster_path, 'w92')
? getTmdbPosterUrl(entry.poster_path, "w92")
: undefined;
const isMovie = entry && !(entry as any).is_tvseries;
if (variant === 'grid') {
if (variant === "grid") {
const gridContent = (
<div className="w-14 shrink-0 rounded overflow-hidden bg-primary/10 hover:bg-primary/20 transition-colors cursor-pointer">
{thumbSrc ? (
@@ -237,7 +293,9 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
/>
) : (
<div className="w-full aspect-2/3 bg-muted/40 flex items-center justify-center">
<span className="text-[7px] text-muted-foreground text-center px-0.5 leading-tight">{entryTitle}</span>
<span className="text-[7px] text-muted-foreground text-center px-0.5 leading-tight">
{entryTitle}
</span>
</div>
)}
<p className="text-[7px] text-center text-muted-foreground tabular-nums py-0.5 leading-tight truncate px-0.5">
@@ -250,7 +308,10 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
<Tooltip>
<TooltipTrigger asChild>
{entryId ? (
<Link to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`} className="block">
<Link
to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`}
className="block"
>
{gridContent}
</Link>
) : (
@@ -274,7 +335,7 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
);
}
if (variant === 'dialog') {
if (variant === "dialog") {
const dialogContent = (
<div className="rounded-lg overflow-hidden bg-primary/10 hover:bg-primary/20 transition-colors cursor-pointer">
{thumbSrc ? (
@@ -285,25 +346,35 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
/>
) : (
<div className="w-full aspect-2/3 bg-muted/40 flex items-center justify-center p-2">
<span className="text-xs text-muted-foreground text-center leading-tight">{entryTitle}</span>
<span className="text-xs text-muted-foreground text-center leading-tight">
{entryTitle}
</span>
</div>
)}
<div className="p-1.5">
<p className="text-xs font-medium leading-tight truncate">{entryTitle}</p>
<p className="text-xs font-medium leading-tight truncate">
{entryTitle}
</p>
{!isMovie && (
<p className="text-[10px] text-muted-foreground tabular-nums leading-tight mt-0.5">
{seasonLabel}{episodeLabel}
{seasonLabel}
{episodeLabel}
</p>
)}
{episode.name && (
<p className="text-[10px] text-muted-foreground leading-tight truncate mt-0.5">{episode.name}</p>
<p className="text-[10px] text-muted-foreground leading-tight truncate mt-0.5">
{episode.name}
</p>
)}
</div>
</div>
);
return entryId ? (
<Link to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`} className="block">
<Link
to={`/entry/${entryId}/season/${seasonId}/episode/${episode.id}`}
className="block"
>
{dialogContent}
</Link>
) : (
@@ -362,12 +433,20 @@ function EpisodeCalendarItem({ episode, variant = 'list' }: { episode: Episode;
);
}
function DayDialog({ date, episodes, onClose }: { date: Date; episodes: Episode[]; onClose: () => void }) {
function DayDialog({
date,
episodes,
onClose,
}: {
date: Date;
episodes: Episode[];
onClose: () => void;
}) {
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{format(date, 'EEEE, MMMM d')}</DialogTitle>
<DialogTitle>{format(date, "EEEE, MMMM d")}</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 max-h-[70vh] overflow-y-auto pr-1">
{episodes.map((ep) => (
+19 -14
View File
@@ -1,26 +1,26 @@
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';
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 [search, setSearch] = useState("");
const debouncedSearch = useDebounce(search, 300);
const [filter, setFilter] = useState<'all' | 'official' | 'custom'>('all');
const [filter, setFilter] = useState<"all" | "official" | "custom">("all");
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const filtered = useMemo(() => {
let result = collections;
if (filter === 'official') {
if (filter === "official") {
result = result.filter((c) => !c.is_user_collection);
} else if (filter === 'custom') {
} else if (filter === "custom") {
result = result.filter((c) => c.is_user_collection);
}
@@ -38,7 +38,7 @@ export function CollectionsPage() {
const paginatedCollections = useMemo(
() => filtered.slice(0, visibleCount),
[filtered, visibleCount]
[filtered, visibleCount],
);
const hasMore = visibleCount < filtered.length;
const loadMore = useCallback(() => setVisibleCount((c) => c + PAGE_SIZE), []);
@@ -60,7 +60,7 @@ export function CollectionsPage() {
<Tabs
value={filter}
onValueChange={(v) => setFilter(v as 'all' | 'official' | 'custom')}
onValueChange={(v) => setFilter(v as "all" | "official" | "custom")}
>
<TabsList>
<TabsTrigger value="all">All</TabsTrigger>
@@ -70,7 +70,12 @@ export function CollectionsPage() {
</Tabs>
</div>
<CollectionsGrid collections={paginatedCollections} isLoading={isLoading} hasMore={hasMore} onLoadMore={loadMore} />
<CollectionsGrid
collections={paginatedCollections}
isLoading={isLoading}
hasMore={hasMore}
onLoadMore={loadMore}
/>
</div>
);
}
+48 -33
View File
@@ -1,19 +1,19 @@
import { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { useLibrary } from '@/hooks/useEntries';
import { useStatistics } from '@/hooks/useStatistics';
import { useLibraryEntries } from '@/stores/useLibraryStore';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Film, Tv, Heart, ListVideo, Clock } from 'lucide-react';
import { formatRuntime, getPosterUrl } from '@/lib/media-utils';
import { WatchActivityChart } from '@/components/dashboard/WatchActivityChart';
import { WatchTimeChart } from '@/components/dashboard/WatchTimeChart';
import { RatingsChart } from '@/components/dashboard/RatingsChart';
import { TopGenresChart } from '@/components/dashboard/TopGenresChart';
import { CouchDayChart } from '@/components/dashboard/CouchDayChart';
import { LibraryGrowthChart } from '@/components/dashboard/LibraryGrowthChart';
import { MediaTypeChart } from '@/components/dashboard/MediaTypeChart';
import { useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { useLibrary } from "@/hooks/useEntries";
import { useStatistics } from "@/hooks/useStatistics";
import { useLibraryEntries } from "@/stores/useLibraryStore";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Film, Tv, Heart, ListVideo, Clock } from "lucide-react";
import { formatRuntime, getPosterUrl } from "@/lib/media-utils";
import { WatchActivityChart } from "@/components/dashboard/WatchActivityChart";
import { WatchTimeChart } from "@/components/dashboard/WatchTimeChart";
import { RatingsChart } from "@/components/dashboard/RatingsChart";
import { TopGenresChart } from "@/components/dashboard/TopGenresChart";
import { CouchDayChart } from "@/components/dashboard/CouchDayChart";
import { LibraryGrowthChart } from "@/components/dashboard/LibraryGrowthChart";
import { MediaTypeChart } from "@/components/dashboard/MediaTypeChart";
export function DashboardPage() {
useLibrary();
@@ -21,43 +21,58 @@ export function DashboardPage() {
const allEntries = useLibraryEntries();
const [watchYear, setWatchYear] = useState(new Date().getFullYear());
const movies = useMemo(() => allEntries.filter((e) => !e.is_tvseries && !e.watchlist), [allEntries]);
const tvSeries = useMemo(() => allEntries.filter((e) => e.is_tvseries && !e.watchlist), [allEntries]);
const favorites = useMemo(() => allEntries.filter((e) => e.favorit && !e.watchlist), [allEntries]);
const watchlist = useMemo(() => allEntries.filter((e) => e.watchlist), [allEntries]);
const movies = useMemo(
() => allEntries.filter((e) => !e.is_tvseries && !e.watchlist),
[allEntries],
);
const tvSeries = useMemo(
() => allEntries.filter((e) => e.is_tvseries && !e.watchlist),
[allEntries],
);
const favorites = useMemo(
() => allEntries.filter((e) => e.favorit && !e.watchlist),
[allEntries],
);
const watchlist = useMemo(
() => allEntries.filter((e) => e.watchlist),
[allEntries],
);
const statCards = [
{
title: 'Movies',
title: "Movies",
value: movies.length,
icon: Film,
color: 'text-blue-500',
color: "text-blue-500",
},
{
title: 'TV Series',
title: "TV Series",
value: tvSeries.length,
icon: Tv,
color: 'text-green-500',
color: "text-green-500",
},
{
title: 'Favorites',
title: "Favorites",
value: favorites.length,
icon: Heart,
color: 'text-red-500',
color: "text-red-500",
},
{
title: 'Watchlist',
title: "Watchlist",
value: watchlist.length,
icon: ListVideo,
color: 'text-purple-500',
color: "text-purple-500",
},
{
title: 'Watch Time',
title: "Watch Time",
value: stats
? formatRuntime((parseInt(stats.series || '0') || 0) + (parseInt(stats.movies || '0') || 0))
: '0h',
? formatRuntime(
(parseInt(stats.series || "0") || 0) +
(parseInt(stats.movies || "0") || 0),
)
: "0h",
icon: Clock,
color: 'text-orange-500',
color: "text-orange-500",
},
];
@@ -108,7 +123,7 @@ export function DashboardPage() {
.sort(
(a, b) =>
new Date(b.date_last_seen!).getTime() -
new Date(a.date_last_seen!).getTime()
new Date(a.date_last_seen!).getTime(),
)
.slice(0, 14)
.map((entry, index) => (
+34 -28
View File
@@ -1,41 +1,41 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { useParams } from 'react-router-dom';
import { useInfiniteQuery } from '@tanstack/react-query';
import { tmdbApi } from '@/api/tmdb';
import { useLibrary } from '@/hooks/useEntries';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { EntryCard, EntryCardSkeleton } from '@/components/entries/EntryCard';
import { Loader2 } from 'lucide-react';
import type { TmdbEntry, TmdbPaginatedResponse } from '@/types';
import { useState, useEffect, useRef, useCallback } from "react";
import { useParams } from "react-router-dom";
import { useInfiniteQuery } from "@tanstack/react-query";
import { tmdbApi } from "@/api/tmdb";
import { useLibrary } from "@/hooks/useEntries";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { EntryCard, EntryCardSkeleton } from "@/components/entries/EntryCard";
import { Loader2 } from "lucide-react";
import type { TmdbEntry, TmdbPaginatedResponse } from "@/types";
const CATEGORY_LABELS: Record<string, string> = {
trending: 'Trending',
popular: 'Popular',
'top-rated': 'Top Rated',
upcoming: 'Upcoming',
trending: "Trending",
popular: "Popular",
"top-rated": "Top Rated",
upcoming: "Upcoming",
};
type MediaTab = 'movie' | 'tv';
type MediaTab = "movie" | "tv";
function useCategoryQuery(category: string, mediaType: MediaTab) {
return useInfiniteQuery<TmdbPaginatedResponse<TmdbEntry>>({
queryKey: ['tmdb', category, mediaType],
queryKey: ["tmdb", category, mediaType],
queryFn: ({ pageParam }) => {
const page = pageParam as number;
switch (category) {
case 'trending':
return mediaType === 'movie'
case "trending":
return mediaType === "movie"
? tmdbApi.getTrendingMovies(page)
: tmdbApi.getTrendingTv(page);
case 'popular':
return mediaType === 'movie'
case "popular":
return mediaType === "movie"
? tmdbApi.getPopularMovies(page)
: tmdbApi.getPopularTv(page);
case 'top-rated':
return mediaType === 'movie'
case "top-rated":
return mediaType === "movie"
? tmdbApi.getTopRatedMovies(page)
: tmdbApi.getTopRatedTv(page);
case 'upcoming':
case "upcoming":
return tmdbApi.getUpcomingMovies(page);
default:
return tmdbApi.getPopularMovies(page);
@@ -48,20 +48,24 @@ function useCategoryQuery(category: string, mediaType: MediaTab) {
}
export function DiscoverPage() {
const { category = 'trending' } = useParams<{ category: string }>();
const [mediaType, setMediaType] = useState<MediaTab>('movie');
const { category = "trending" } = useParams<{ category: string }>();
const [mediaType, setMediaType] = useState<MediaTab>("movie");
const sentinelRef = useRef<HTMLDivElement>(null);
useLibrary();
const isUpcoming = category === 'upcoming';
const isUpcoming = category === "upcoming";
const query = useCategoryQuery(category, mediaType);
const entries = query.data?.pages.flatMap((p) => p.results) ?? [];
// Infinite scroll via IntersectionObserver
const handleIntersect = useCallback(
(entries: IntersectionObserverEntry[]) => {
if (entries[0]?.isIntersecting && query.hasNextPage && !query.isFetchingNextPage) {
if (
entries[0]?.isIntersecting &&
query.hasNextPage &&
!query.isFetchingNextPage
) {
query.fetchNextPage();
}
},
@@ -71,12 +75,14 @@ export function DiscoverPage() {
useEffect(() => {
const el = sentinelRef.current;
if (!el) return;
const observer = new IntersectionObserver(handleIntersect, { rootMargin: '400px' });
const observer = new IntersectionObserver(handleIntersect, {
rootMargin: "400px",
});
observer.observe(el);
return () => observer.disconnect();
}, [handleIntersect]);
const title = CATEGORY_LABELS[category] || 'Discover';
const title = CATEGORY_LABELS[category] || "Discover";
return (
<div className="space-y-6 animate-page-enter">
+97 -57
View File
@@ -1,69 +1,83 @@
import { useState, useMemo, useEffect, useRef } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useEntry, useEntryCredits } from '@/hooks/useEntries';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useState, useMemo, useEffect, useRef } from "react";
import { useParams, Link } from "react-router-dom";
import { useEntry, useEntryCredits } from "@/hooks/useEntries";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { getProfileUrl } from '@/lib/media-utils';
import { ArrowUpDown } from 'lucide-react';
import type { Credit } from '@/types';
} from "@/components/ui/select";
import { getProfileUrl } from "@/lib/media-utils";
import { ArrowUpDown } from "lucide-react";
import type { Credit } from "@/types";
type SortField = 'order' | 'popularity' | 'name' | 'birthday' | 'gender' | 'episode_count';
type SortDir = 'asc' | 'desc';
type CastFilter = 'all' | 'cast' | 'crew';
type SortField =
| "order"
| "popularity"
| "name"
| "birthday"
| "gender"
| "episode_count";
type SortDir = "asc" | "desc";
type CastFilter = "all" | "cast" | "crew";
const PAGE_SIZE = 24;
const SORT_LABELS: Record<SortField, string> = {
order: 'Credit Order',
popularity: 'Popularity',
name: 'Name',
birthday: 'Birthday',
gender: 'Gender',
episode_count: 'Episodes',
order: "Credit Order",
popularity: "Popularity",
name: "Name",
birthday: "Birthday",
gender: "Gender",
episode_count: "Episodes",
};
const FILTER_LABELS: Record<CastFilter, string> = {
all: 'All',
cast: 'Cast',
crew: 'Crew',
all: "All",
cast: "Cast",
crew: "Crew",
};
function sortCredits(credits: Credit[], field: SortField, dir: SortDir): Credit[] {
function sortCredits(
credits: Credit[],
field: SortField,
dir: SortDir,
): Credit[] {
return [...credits].sort((a, b) => {
let cmp = 0;
switch (field) {
case 'order':
case "order":
cmp = (a.order ?? 9999) - (b.order ?? 9999);
break;
case 'popularity':
case "popularity":
cmp = (b.people?.popularity ?? 0) - (a.people?.popularity ?? 0);
break;
case 'name':
cmp = (a.people?.name ?? '').localeCompare(b.people?.name ?? '');
case "name":
cmp = (a.people?.name ?? "").localeCompare(b.people?.name ?? "");
break;
case 'birthday': {
const da = a.people?.birthday ? new Date(a.people.birthday).getTime() : 0;
const db = b.people?.birthday ? new Date(b.people.birthday).getTime() : 0;
case "birthday": {
const da = a.people?.birthday
? new Date(a.people.birthday).getTime()
: 0;
const db = b.people?.birthday
? new Date(b.people.birthday).getTime()
: 0;
cmp = da - db;
break;
}
case 'gender':
case "gender":
cmp = (a.people?.gender ?? 0) - (b.people?.gender ?? 0);
break;
case 'episode_count':
case "episode_count":
cmp = (b.episode_count ?? 0) - (a.episode_count ?? 0);
break;
}
return dir === 'asc' ? cmp : -cmp;
return dir === "asc" ? cmp : -cmp;
});
}
@@ -71,38 +85,51 @@ export function EntryCastsPage() {
const { id } = useParams<{ id: string }>();
const entryId = parseInt(id!, 10);
const { data: entry, isLoading } = useEntry(entryId);
const { data: allCredits = [], isLoading: creditsLoading } = useEntryCredits(entryId);
const { data: allCredits = [], isLoading: creditsLoading } =
useEntryCredits(entryId);
const [sortField, setSortField] = useState<SortField>('episode_count');
const [sortDir, setSortDir] = useState<SortDir>('asc');
const [filter, setFilter] = useState<CastFilter>('cast');
const [search, setSearch] = useState('');
const [sortField, setSortField] = useState<SortField>("episode_count");
const [sortDir, setSortDir] = useState<SortDir>("asc");
const [filter, setFilter] = useState<CastFilter>("cast");
const [search, setSearch] = useState("");
const [visibleCount, setVisibleCount] = useState(PAGE_SIZE);
const filtered = useMemo(() => {
if (!allCredits) return [];
let result = allCredits;
if (filter === 'cast') result = result.filter((c) => c.cast_type === 'cast');
else if (filter === 'crew') result = result.filter((c) => c.cast_type === 'crew');
if (filter === "cast")
result = result.filter((c) => c.cast_type === "cast");
else if (filter === "crew")
result = result.filter((c) => c.cast_type === "crew");
if (search.trim()) {
const q = search.trim().toLowerCase();
result = result.filter((c) => {
const name = c.people?.name?.toLowerCase() ?? '';
const role = (c.cast_type === 'cast' ? c.character : (c.job || c.department))?.toLowerCase() ?? '';
const name = c.people?.name?.toLowerCase() ?? "";
const role =
(c.cast_type === "cast"
? c.character
: c.job || c.department
)?.toLowerCase() ?? "";
return name.includes(q) || role.includes(q);
});
}
return result;
}, [allCredits, filter, search]);
const sorted = useMemo(() => sortCredits(filtered, sortField, sortDir), [filtered, sortField, sortDir]);
const sorted = useMemo(
() => sortCredits(filtered, sortField, sortDir),
[filtered, sortField, sortDir],
);
// Reset visible window whenever filter/sort/search changes
useEffect(() => {
setVisibleCount(PAGE_SIZE);
}, [filter, sortField, sortDir, search]);
const visible = useMemo(() => sorted.slice(0, visibleCount), [sorted, visibleCount]);
const visible = useMemo(
() => sorted.slice(0, visibleCount),
[sorted, visibleCount],
);
const hasMore = visibleCount < sorted.length;
// IntersectionObserver-based lazy load on scroll
@@ -117,7 +144,7 @@ export function EntryCastsPage() {
setVisibleCount((c) => Math.min(c + PAGE_SIZE, sorted.length));
}
},
{ rootMargin: '400px 0px' }
{ rootMargin: "400px 0px" },
);
observer.observe(node);
return () => observer.disconnect();
@@ -165,12 +192,15 @@ export function EntryCastsPage() {
className="w-48"
/>
<span className="text-sm text-muted-foreground whitespace-nowrap">
{sorted.length} {sorted.length === 1 ? 'credit' : 'credits'}
{sorted.length} {sorted.length === 1 ? "credit" : "credits"}
</span>
{/* Right: filter + sort */}
<div className="flex items-center gap-3 ml-auto">
<Select value={filter} onValueChange={(v) => setFilter(v as CastFilter)}>
<Select
value={filter}
onValueChange={(v) => setFilter(v as CastFilter)}
>
<SelectTrigger className="w-32">
<SelectValue>{FILTER_LABELS[filter]}</SelectValue>
</SelectTrigger>
@@ -181,7 +211,10 @@ export function EntryCastsPage() {
</SelectContent>
</Select>
<Select value={sortField} onValueChange={(v) => setSortField(v as SortField)}>
<Select
value={sortField}
onValueChange={(v) => setSortField(v as SortField)}
>
<SelectTrigger className="w-40">
<SelectValue>{SORT_LABELS[sortField]}</SelectValue>
</SelectTrigger>
@@ -199,7 +232,7 @@ export function EntryCastsPage() {
variant="ghost"
size="icon"
className="h-9 w-9"
onClick={() => setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'))}
onClick={() => setSortDir((d) => (d === "asc" ? "desc" : "asc"))}
>
<ArrowUpDown className="h-4 w-4" />
</Button>
@@ -208,7 +241,9 @@ export function EntryCastsPage() {
{/* Grid */}
{sorted.length === 0 ? (
<p className="text-center text-muted-foreground py-12">No credits found.</p>
<p className="text-center text-muted-foreground py-12">
No credits found.
</p>
) : (
<>
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
@@ -219,7 +254,9 @@ export function EntryCastsPage() {
{hasMore && (
<div ref={sentinelRef} className="flex justify-center py-6">
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 w-full">
{Array.from({ length: Math.min(PAGE_SIZE, sorted.length - visibleCount) }).map((_, i) => (
{Array.from({
length: Math.min(PAGE_SIZE, sorted.length - visibleCount),
}).map((_, i) => (
<div key={i} className="flex flex-col items-center gap-2 p-2">
<Skeleton className="h-32 w-32 rounded-full" />
<Skeleton className="h-3 w-16" />
@@ -244,7 +281,7 @@ function CreditCard({ credit, isTv }: { credit: Credit; isTv: boolean }) {
: `/people/tmdb/${credit.people?.tmdb_id ?? credit.people_id}`;
const roleLabel =
credit.cast_type === 'cast'
credit.cast_type === "cast"
? credit.character
: credit.job || credit.department;
@@ -257,13 +294,15 @@ function CreditCard({ credit, isTv }: { credit: Credit; isTv: boolean }) {
<AvatarImage src={profileUrl} alt={credit.people?.name} />
<AvatarFallback className="text-sm">
{credit.people?.name
?.split(' ')
?.split(" ")
.map((n) => n[0])
.join('')}
.join("")}
</AvatarFallback>
</Avatar>
<div className="min-w-0 w-full">
<p className="text-sm font-medium leading-tight line-clamp-2">{credit.people?.name}</p>
<p className="text-sm font-medium leading-tight line-clamp-2">
{credit.people?.name}
</p>
{roleLabel && (
<p className="text-xs text-muted-foreground leading-tight line-clamp-1 mt-0.5">
{roleLabel}
@@ -271,7 +310,8 @@ function CreditCard({ credit, isTv }: { credit: Credit; isTv: boolean }) {
)}
{isTv && credit.episode_count != null && credit.episode_count > 0 && (
<p className="text-xs text-muted-foreground/70 leading-tight mt-0.5">
{credit.episode_count} {credit.episode_count === 1 ? 'episode' : 'episodes'}
{credit.episode_count}{" "}
{credit.episode_count === 1 ? "episode" : "episodes"}
</p>
)}
</div>
+68 -37
View File
@@ -1,26 +1,32 @@
import { useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { seasonsApi } from '@/api/seasons';
import { useSeason } from '@/hooks/useSeasons';
import { useEntry, useEntrySeasons } from '@/hooks/useEntries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { useState } from "react";
import { useParams, useNavigate, Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { seasonsApi } from "@/api/seasons";
import { useSeason } from "@/hooks/useSeasons";
import { useEntry, useEntrySeasons } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import {
useEpisodeSeenByEpisode,
useDeleteEpisodeSeen,
} from '@/hooks/useEpisodeSeen';
import { StreamingDialog } from '@/components/streaming/StreamingDialog';
import { useStreamingStore } from '@/stores/useStreamingStore';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { EpisodeWatchHistory } from '@/components/entries/EpisodeWatchHistory';
import { EpisodeSeenEditDialog } from '@/components/dialogs/EpisodeSeenEditDialog';
import { ConfirmDialog } from '@/components/dialogs/ConfirmDialog';
import { CastList } from '@/components/entries/CastList';
import { Eye, ChevronLeft, ChevronRight, Clock, PlayCircle } from 'lucide-react';
import { getTmdbPosterUrl, formatDate, formatRuntime } from '@/lib/media-utils';
import type { Episode, EpisodeSeen } from '@/types';
} from "@/hooks/useEpisodeSeen";
import { StreamingDialog } from "@/components/streaming/StreamingDialog";
import { useStreamingStore } from "@/stores/useStreamingStore";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { EpisodeWatchHistory } from "@/components/entries/EpisodeWatchHistory";
import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog";
import { ConfirmDialog } from "@/components/dialogs/ConfirmDialog";
import { CastList } from "@/components/entries/CastList";
import {
Eye,
ChevronLeft,
ChevronRight,
Clock,
PlayCircle,
} from "lucide-react";
import { getTmdbPosterUrl, formatDate, formatRuntime } from "@/lib/media-utils";
import type { Episode, EpisodeSeen } from "@/types";
export function EpisodePage() {
const { entryId, seasonId, episodeId } = useParams<{
@@ -31,14 +37,16 @@ export function EpisodePage() {
const navigate = useNavigate();
const { data: episodes = [] } = useQuery({
queryKey: ['seasons', parseInt(seasonId!, 10), 'episodes'],
queryKey: ["seasons", parseInt(seasonId!, 10), "episodes"],
queryFn: () => seasonsApi.getEpisodes(parseInt(seasonId!, 10)),
});
const { data: season } = useSeason(parseInt(seasonId!, 10));
const { data: entry } = useEntry(parseInt(entryId!, 10));
const { data: entrySeasons } = useEntrySeasons(parseInt(entryId!, 10));
const entryTitle = entry?.title ?? useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title;
const entryTitle =
entry?.title ??
useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title;
const seasonNumber = season?.season_number;
const { initialize, play } = useStreamingStore();
@@ -46,7 +54,9 @@ export function EpisodePage() {
const epId = parseInt(episodeId!, 10);
const entryIdNum = parseInt(entryId!, 10);
const episode: Episode | undefined = episodes.find((ep: Episode) => ep.id === epId);
const episode: Episode | undefined = episodes.find(
(ep: Episode) => ep.id === epId,
);
const { data: watchHistory = [] } = useEpisodeSeenByEpisode(epId);
const deleteEpisodeSeen = useDeleteEpisodeSeen();
@@ -56,7 +66,8 @@ export function EpisodePage() {
// Find prev/next episode
const currentIndex = episodes.findIndex((ep: Episode) => ep.id === epId);
const prevEpisode: Episode | undefined = currentIndex > 0 ? episodes[currentIndex - 1] : undefined;
const prevEpisode: Episode | undefined =
currentIndex > 0 ? episodes[currentIndex - 1] : undefined;
const nextEpisode: Episode | undefined =
currentIndex < episodes.length - 1 ? episodes[currentIndex + 1] : undefined;
@@ -78,24 +89,27 @@ export function EpisodePage() {
to={`/entry/${entryId}`}
className="hover:text-foreground transition-colors truncate max-w-50"
>
{entryTitle || 'Entry'}
{entryTitle || "Entry"}
</Link>
<span>/</span>
<Link
to={`/entry/${entryId}/season/${seasonId}`}
className="hover:text-foreground transition-colors"
>
Season {seasonNumber ?? '?'}
Season {seasonNumber ?? "?"}
</Link>
<span>/</span>
<span className="text-foreground font-medium">Episode {episode.episode_number}</span>
<span className="text-foreground font-medium">
Episode {episode.episode_number}
</span>
</div>
{/* Top bar: nav breadcrumb + Mark Watched */}
<div className="flex items-center justify-between gap-4">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span className="font-medium text-foreground">
S{String(seasonNumber ?? 0).padStart(2, '0')} E{String(episode.episode_number).padStart(2, '0')}
S{String(seasonNumber ?? 0).padStart(2, "0")} E
{String(episode.episode_number).padStart(2, "0")}
</span>
</div>
<Button size="sm" onClick={() => setShowAddDialog(true)}>
@@ -112,7 +126,7 @@ export function EpisodePage() {
if (!entry?.entryIds?.tmdb_id || !seasonNumber) return;
initialize();
play({
type: 'tv',
type: "tv",
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season: seasonNumber,
@@ -122,14 +136,16 @@ export function EpisodePage() {
}}
>
<img
src={getTmdbPosterUrl(episode.still_path, 'w1280')}
src={getTmdbPosterUrl(episode.still_path, "w1280")}
alt={episode.name}
className="w-full max-h-96 object-cover transition-[filter] group-hover:brightness-50"
/>
<div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
<div className="flex items-center gap-2 bg-black/60 backdrop-blur-sm rounded-full px-5 py-2.5">
<PlayCircle className="h-6 w-6 text-white" />
<span className="text-white font-medium text-sm">Watch Episode</span>
<span className="text-white font-medium text-sm">
Watch Episode
</span>
</div>
</div>
</div>
@@ -171,7 +187,9 @@ export function EpisodePage() {
<EpisodeWatchHistory
watchHistory={watchHistory}
onEdit={(id) => {
const rec = watchHistory.find((r) => r.id === id) as EpisodeSeen | undefined;
const rec = watchHistory.find((r) => r.id === id) as
| EpisodeSeen
| undefined;
if (rec) setEditRecord(rec);
}}
onDelete={(id) => setDeleteTarget(id)}
@@ -188,7 +206,9 @@ export function EpisodePage() {
size="sm"
className="flex items-center gap-1 max-w-60"
onClick={() =>
navigate(`/entry/${entryId}/season/${seasonId}/episode/${prevEpisode.id}`)
navigate(
`/entry/${entryId}/season/${seasonId}/episode/${prevEpisode.id}`,
)
}
>
<ChevronLeft className="h-4 w-4 shrink-0" />
@@ -205,7 +225,9 @@ export function EpisodePage() {
size="sm"
className="flex items-center gap-1 max-w-60 ml-auto"
onClick={() =>
navigate(`/entry/${entryId}/season/${seasonId}/episode/${nextEpisode.id}`)
navigate(
`/entry/${entryId}/season/${seasonId}/episode/${nextEpisode.id}`,
)
}
>
<span className="truncate">
@@ -234,7 +256,9 @@ export function EpisodePage() {
{editRecord && (
<EpisodeSeenEditDialog
open={!!editRecord}
onOpenChange={(open) => { if (!open) setEditRecord(null); }}
onOpenChange={(open) => {
if (!open) setEditRecord(null);
}}
mode="edit"
record={editRecord}
entryId={entryIdNum}
@@ -245,14 +269,21 @@ export function EpisodePage() {
{/* Delete confirm dialog */}
<ConfirmDialog
open={deleteTarget !== null}
onOpenChange={(open) => { if (!open) setDeleteTarget(null); }}
onOpenChange={(open) => {
if (!open) setDeleteTarget(null);
}}
title="Delete Watch Record"
description="Are you sure you want to remove this watch record? This cannot be undone."
confirmLabel="Delete"
variant="destructive"
onConfirm={() => {
if (deleteTarget !== null) {
deleteEpisodeSeen.mutate({ id: deleteTarget, entryId: entryIdNum, episodeId: epId, seasonId: parseInt(seasonId!, 10) });
deleteEpisodeSeen.mutate({
id: deleteTarget,
entryId: entryIdNum,
episodeId: epId,
seasonId: parseInt(seasonId!, 10),
});
setDeleteTarget(null);
}
}}
+35 -29
View File
@@ -1,22 +1,26 @@
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';
import { Search } from 'lucide-react';
import { getMediaUrl } from '@/lib/api';
import type { Media } from '@/types';
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";
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 [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 [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();
@@ -34,7 +38,7 @@ export function MediaPage() {
if (node) observerRef.current.observe(node);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[isLoading]
[isLoading],
);
useEffect(() => {
@@ -54,13 +58,13 @@ export function MediaPage() {
const filtered = useMemo(() => {
let result = allMedias;
if (mediaType !== 'all') {
if (mediaType !== "all") {
result = result.filter((m) => m.type === mediaType);
}
if (customFilter === 'custom') {
if (customFilter === "custom") {
result = result.filter((m) => m.is_custom);
} else if (customFilter === 'official') {
} else if (customFilter === "official") {
result = result.filter((m) => !m.is_custom);
}
@@ -78,7 +82,7 @@ export function MediaPage() {
const paginatedMedia = useMemo(
() => filtered.slice(0, visibleCount),
[filtered, visibleCount]
[filtered, visibleCount],
);
const hasMore = visibleCount < filtered.length;
@@ -129,9 +133,9 @@ export function MediaPage() {
<Skeleton
key={i}
className={
mediaType === 'backdrop'
? 'aspect-video w-full rounded-lg'
: 'aspect-[2/3] w-full rounded-lg'
mediaType === "backdrop"
? "aspect-video w-full rounded-lg"
: "aspect-[2/3] w-full rounded-lg"
}
/>
))}
@@ -143,27 +147,29 @@ export function MediaPage() {
) : (
<div
className={`grid gap-4 ${
mediaType === 'backdrop'
? 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3'
: 'grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6'
mediaType === "backdrop"
? "grid-cols-1 sm:grid-cols-2 lg:grid-cols-3"
: "grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6"
}`}
>
{paginatedMedia.map((media, index) => (
<div
key={media.id}
ref={index === paginatedMedia.length - 1 ? lastItemRef : undefined}
ref={
index === paginatedMedia.length - 1 ? lastItemRef : undefined
}
className="group relative overflow-hidden rounded-lg bg-muted"
>
<img
src={getMediaUrl(
'entries',
"entries",
`${media.type}s`,
'preview',
media.path
"preview",
media.path,
)}
alt={media.entryTitle}
className={`w-full object-cover ${
media.type === 'backdrop' ? 'aspect-video' : 'aspect-[2/3]'
media.type === "backdrop" ? "aspect-video" : "aspect-[2/3]"
}`}
loading="lazy"
/>
+50 -26
View File
@@ -1,22 +1,22 @@
import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { usePopularPeople, useTmdbSearchPeople } from '@/hooks/useTmdb';
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';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Search, Heart } from 'lucide-react';
import { getProfileUrl } from '@/lib/media-utils';
import { useState, useCallback, useRef, useEffect, useMemo } from "react";
import { Link } from "react-router-dom";
import { usePopularPeople, useTmdbSearchPeople } from "@/hooks/useTmdb";
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";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Search, Heart } from "lucide-react";
import { getProfileUrl } from "@/lib/media-utils";
type PeopleFilter = 'all' | 'favorite';
type PeopleFilter = "all" | "favorite";
export function PeoplePage() {
const [search, setSearch] = useState('');
const [debouncedSearch, setDebouncedSearch] = useState('');
const [filter, setFilter] = useState<PeopleFilter>('all');
const [search, setSearch] = useState("");
const [debouncedSearch, setDebouncedSearch] = useState("");
const [filter, setFilter] = useState<PeopleFilter>("all");
const [localOnly, setLocalOnly] = useState(false);
// Debounce search input
@@ -28,16 +28,21 @@ export function PeoplePage() {
const isSearching = debouncedSearch.length > 0;
const popularQuery = usePopularPeople();
const tmdbSearchQuery = useTmdbSearchPeople(localOnly ? '' : debouncedSearch);
const tmdbSearchQuery = useTmdbSearchPeople(localOnly ? "" : debouncedSearch);
// Paginated local people (handles both search and browse)
const localPeopleQuery = useLocalPeopleInfinite(
localOnly ? debouncedSearch : '',
localOnly ? debouncedSearch : "",
localOnly,
);
// For TMDB mode, use infinite scroll queries
const activeQuery = isSearching && !localOnly ? tmdbSearchQuery : !localOnly ? popularQuery : null;
const activeQuery =
isSearching && !localOnly
? tmdbSearchQuery
: !localOnly
? popularQuery
: null;
const tmdbPeople = activeQuery?.data?.pages.flatMap((p) => p.results) ?? [];
// Flatten paginated local results
@@ -49,7 +54,7 @@ export function PeoplePage() {
// Apply client-side favorite filter
const filteredLocalPeople = useMemo(() => {
if (!localOnly) return [];
if (filter === 'favorite') {
if (filter === "favorite") {
return allLocalPeople.filter((p: any) => p.favorite);
}
return allLocalPeople;
@@ -68,16 +73,31 @@ export function PeoplePage() {
observerRef.current = new IntersectionObserver((entries) => {
if (!entries[0].isIntersecting) return;
if (localOnly) {
if (localPeopleQuery.hasNextPage && !localPeopleQuery.isFetchingNextPage) {
if (
localPeopleQuery.hasNextPage &&
!localPeopleQuery.isFetchingNextPage
) {
localPeopleQuery.fetchNextPage();
}
} else if (activeQuery && !activeQuery.isFetchingNextPage && activeQuery.hasNextPage) {
} else if (
activeQuery &&
!activeQuery.isFetchingNextPage &&
activeQuery.hasNextPage
) {
activeQuery.fetchNextPage();
}
});
observerRef.current.observe(node);
},
[localOnly, localPeopleQuery.hasNextPage, localPeopleQuery.isFetchingNextPage, localPeopleQuery.fetchNextPage, activeQuery?.isFetchingNextPage, activeQuery?.hasNextPage, activeQuery?.fetchNextPage]
[
localOnly,
localPeopleQuery.hasNextPage,
localPeopleQuery.isFetchingNextPage,
localPeopleQuery.fetchNextPage,
activeQuery?.isFetchingNextPage,
activeQuery?.hasNextPage,
activeQuery?.fetchNextPage,
],
);
useEffect(() => {
@@ -160,7 +180,11 @@ export function PeoplePage() {
style={{ animationDelay: `${Math.min(index * 20, 300)}ms` }}
>
<Link
to={localOnly ? `/people/${person.id}` : `/people/tmdb/${person.id}`}
to={
localOnly
? `/people/${person.id}`
: `/people/tmdb/${person.id}`
}
className="group flex flex-col items-center gap-2 text-center"
>
<div className="relative">
@@ -171,9 +195,9 @@ export function PeoplePage() {
/>
<AvatarFallback>
{person.name
.split(' ')
.split(" ")
.map((n: string) => n[0])
.join('')}
.join("")}
</AvatarFallback>
</Avatar>
{person.favorite && (
+135 -48
View File
@@ -1,30 +1,37 @@
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { useState, useEffect } from 'react';
import { useParams, useNavigate, useLocation } from "react-router-dom";
import { useState, useEffect } from "react";
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';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
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, Plus, Loader2, ExternalLink } from 'lucide-react';
import type { TmdbEntry } from '@/types';
import type { TmdbFilmographyItem } from '@/api/people';
} from "@/hooks/usePeople";
import { useLibrary } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import { Skeleton } from "@/components/ui/skeleton";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
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,
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';
const TMDB_IMG = "https://image.tmdb.org/t/p";
export function PersonDetailsPage() {
const { id, tmdbId } = useParams<{ id?: string; tmdbId?: string }>();
const location = useLocation();
const isTmdbMode = location.pathname.startsWith('/people/tmdb/');
const isTmdbMode = location.pathname.startsWith("/people/tmdb/");
if (isTmdbMode && tmdbId) {
return <TmdbPersonView tmdbId={parseInt(tmdbId, 10)} />;
@@ -38,7 +45,8 @@ export function PersonDetailsPage() {
function LocalPersonView({ personId }: { personId: number }) {
const navigate = useNavigate();
const { data: person, isLoading, isError } = usePerson(personId);
const { data: tmdbFilmography, isLoading: tmdbLoading } = usePersonTmdbFilmography(personId);
const { data: tmdbFilmography, isLoading: tmdbLoading } =
usePersonTmdbFilmography(personId);
const updatePerson = useUpdatePerson();
useLibrary();
const libraryMap = useLibraryStore((s) => s.entries);
@@ -51,7 +59,7 @@ function LocalPersonView({ personId }: { personId: number }) {
<p className="text-sm text-muted-foreground">
This person could not be loaded. They may not exist in the database.
</p>
<Button variant="outline" onClick={() => navigate('/people')}>
<Button variant="outline" onClick={() => navigate("/people")}>
Back to People
</Button>
</div>
@@ -66,9 +74,15 @@ function LocalPersonView({ personId }: { personId: number }) {
<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} />
<AvatarImage
src={getProfileUrl(person.profile_path)}
alt={person.name}
/>
<AvatarFallback className="text-2xl sm:text-3xl">
{person.name.split(' ').map((n: string) => n[0]).join('')}
{person.name
.split(" ")
.map((n: string) => n[0])
.join("")}
</AvatarFallback>
</Avatar>
<div className="space-y-2 text-center sm:text-left sm:space-y-3">
@@ -78,10 +92,17 @@ function LocalPersonView({ personId }: { personId: number }) {
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => updatePerson.mutate({ id: person.id, data: { favorite: !person.favorite } })}
onClick={() =>
updatePerson.mutate({
id: person.id,
data: { favorite: !person.favorite },
})
}
disabled={updatePerson.isPending}
>
<Heart className={`h-5 w-5 ${person.favorite ? 'fill-red-500 text-red-500' : 'text-muted-foreground'}`} />
<Heart
className={`h-5 w-5 ${person.favorite ? "fill-red-500 text-red-500" : "text-muted-foreground"}`}
/>
</Button>
</div>
<PersonMeta
@@ -135,7 +156,9 @@ function TmdbPersonView({ tmdbId }: { tmdbId: number }) {
<p className="text-sm text-muted-foreground">
Could not load person data from TMDB.
</p>
<Button variant="outline" onClick={() => navigate(-1)}>Go back</Button>
<Button variant="outline" onClick={() => navigate(-1)}>
Go back
</Button>
</div>
);
}
@@ -167,19 +190,26 @@ function TmdbPersonView({ tmdbId }: { tmdbId: number }) {
<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('')}
{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">
<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'}
{fetchPerson.isPending ? "Adding..." : "Add to Library"}
</Button>
</div>
<PersonMeta
@@ -227,9 +257,24 @@ function PersonMeta({
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></>)}
{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>
@@ -266,17 +311,26 @@ function PersonSkeleton() {
/* ─── Filmography ─── */
interface FilmographySectionProps {
libraryMap: Map<number, import('@/types').Entry>;
libraryMap: Map<number, import("@/types").Entry>;
libraryLoaded: boolean;
tmdbFilmography?: { cast: TmdbFilmographyItem[]; crew: TmdbFilmographyItem[] };
tmdbFilmography?: {
cast: TmdbFilmographyItem[];
crew: TmdbFilmographyItem[];
};
tmdbLoading: boolean;
}
function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLoading }: FilmographySectionProps) {
function FilmographySection({
libraryMap,
libraryLoaded,
tmdbFilmography,
tmdbLoading,
}: FilmographySectionProps) {
const [libraryPage, setLibraryPage] = useState(0);
const [otherPage, setOtherPage] = useState(0);
const PAGE_SIZE = 6; // 6 cols × 1 row
const GRID = 'grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl: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 (
@@ -293,7 +347,9 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
const allTmdbCredits = [
...(tmdbFilmography?.cast ?? []),
...(tmdbFilmography?.crew?.filter((c) => c.job === 'Director' || c.department === 'Directing') ?? []),
...(tmdbFilmography?.crew?.filter(
(c) => c.job === "Director" || c.department === "Directing",
) ?? []),
];
const seenTmdbIds = new Set<number>();
const dedupedCredits = allTmdbCredits.filter((c) => {
@@ -302,7 +358,7 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
return true;
});
const tmdbIdToLibraryEntry = new Map<number, import('@/types').Entry>();
const tmdbIdToLibraryEntry = new Map<number, import("@/types").Entry>();
for (const entry of libraryMap.values()) {
if (entry.entryIds?.tmdb_id != null) {
tmdbIdToLibraryEntry.set(Number(entry.entryIds.tmdb_id), entry);
@@ -310,14 +366,23 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
}
// Sort by popularity descending
const sorted = [...dedupedCredits].sort((a, b) => (b.popularity ?? 0) - (a.popularity ?? 0));
const sorted = [...dedupedCredits].sort(
(a, b) => (b.popularity ?? 0) - (a.popularity ?? 0),
);
const libraryCredits = 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';
return (
lower === "self" ||
lower.startsWith("self -") ||
lower.startsWith("self (") ||
lower === "themselves" ||
lower === "himself" ||
lower === "herself"
);
};
const otherCreditsSorted = sorted
.filter((c) => !tmdbIdToLibraryEntry.has(c.id))
@@ -326,8 +391,12 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
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();
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;
@@ -341,8 +410,14 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
);
}
const librarySlice = libraryCredits.slice(libraryPage * PAGE_SIZE, (libraryPage + 1) * PAGE_SIZE);
const otherSlice = otherCredits.slice(otherPage * PAGE_SIZE, (otherPage + 1) * PAGE_SIZE);
const librarySlice = libraryCredits.slice(
libraryPage * PAGE_SIZE,
(libraryPage + 1) * PAGE_SIZE,
);
const otherSlice = otherCredits.slice(
otherPage * PAGE_SIZE,
(otherPage + 1) * PAGE_SIZE,
);
const libraryTotalPages = Math.ceil(libraryCredits.length / PAGE_SIZE);
const otherTotalPages = Math.ceil(otherCredits.length / PAGE_SIZE);
@@ -359,7 +434,9 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
{libraryTotalPages > 1 && (
<div className="flex items-center gap-1">
<Button
variant="ghost" size="icon" className="h-7 w-7"
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={libraryPage === 0}
onClick={() => setLibraryPage((p) => p - 1)}
>
@@ -369,7 +446,9 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
{libraryPage + 1}/{libraryTotalPages}
</span>
<Button
variant="ghost" size="icon" className="h-7 w-7"
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={libraryPage === libraryTotalPages - 1}
onClick={() => setLibraryPage((p) => p + 1)}
>
@@ -385,7 +464,9 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
<div key={credit.id} className="space-y-1">
<EntryCard entry={entry} />
{credit.character && (
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">{credit.character}</p>
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">
{credit.character}
</p>
)}
</div>
);
@@ -403,7 +484,9 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
{otherTotalPages > 1 && (
<div className="flex items-center gap-1">
<Button
variant="ghost" size="icon" className="h-7 w-7"
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={otherPage === 0}
onClick={() => setOtherPage((p) => p - 1)}
>
@@ -413,7 +496,9 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
{otherPage + 1}/{otherTotalPages}
</span>
<Button
variant="ghost" size="icon" className="h-7 w-7"
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={otherPage === otherTotalPages - 1}
onClick={() => setOtherPage((p) => p + 1)}
>
@@ -433,7 +518,7 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
release_date: credit.release_date,
first_air_date: credit.first_air_date,
media_type: credit.media_type,
overview: '',
overview: "",
vote_average: 0,
vote_count: 0,
genre_ids: [],
@@ -443,7 +528,9 @@ function FilmographySection({ libraryMap, libraryLoaded, tmdbFilmography, tmdbLo
<div key={credit.id} className="space-y-1">
<EntryCard tmdbEntry={tmdbEntry} />
{credit.character && (
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">{credit.character}</p>
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">
{credit.character}
</p>
)}
</div>
);
@@ -1,19 +1,22 @@
import { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useTmdbPersonPreview, useFetchPersonByTmdbId } from '@/hooks/usePeople';
import { useLibrary } from '@/hooks/useEntries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { Skeleton } from '@/components/ui/skeleton';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
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 { Plus, Loader2, ChevronLeft, ChevronRight } from 'lucide-react';
import type { TmdbEntry } from '@/types';
import type { TmdbFilmographyItem } from '@/api/people';
import { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import {
useTmdbPersonPreview,
useFetchPersonByTmdbId,
} from "@/hooks/usePeople";
import { useLibrary } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import { Skeleton } from "@/components/ui/skeleton";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
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 { Plus, Loader2, ChevronLeft, ChevronRight } from "lucide-react";
import type { TmdbEntry } from "@/types";
import type { TmdbFilmographyItem } from "@/api/people";
const TMDB_IMG = 'https://image.tmdb.org/t/p';
const TMDB_IMG = "https://image.tmdb.org/t/p";
export function PersonTmdbRedirectPage() {
const { tmdbId } = useParams<{ tmdbId: string }>();
@@ -48,7 +51,9 @@ export function PersonTmdbRedirectPage() {
<p className="text-sm text-muted-foreground">
Could not load person data from TMDB.
</p>
<Button variant="outline" onClick={() => navigate(-1)}>Go back</Button>
<Button variant="outline" onClick={() => navigate(-1)}>
Go back
</Button>
</div>
);
}
@@ -71,26 +76,50 @@ export function PersonTmdbRedirectPage() {
<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('')}
{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">
<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'}
{fetchPerson.isPending ? "Adding..." : "Add to Library"}
</Button>
</div>
<div className="flex flex-wrap items-center justify-center gap-2 text-sm text-muted-foreground sm:justify-start sm:gap-3">
{preview.known_for_department && <span>{preview.known_for_department}</span>}
{preview.birthday && (<><span>•</span><span>Born: {formatDate(preview.birthday)}</span></>)}
{preview.deathday && (<><span>•</span><span>Died: {formatDate(preview.deathday)}</span></>)}
{preview.place_of_birth && (<><span>•</span><span>{preview.place_of_birth}</span></>)}
{preview.known_for_department && (
<span>{preview.known_for_department}</span>
)}
{preview.birthday && (
<>
<span>•</span>
<span>Born: {formatDate(preview.birthday)}</span>
</>
)}
{preview.deathday && (
<>
<span>•</span>
<span>Died: {formatDate(preview.deathday)}</span>
</>
)}
{preview.place_of_birth && (
<>
<span>•</span>
<span>{preview.place_of_birth}</span>
</>
)}
</div>
{preview.biography && (
<p className="text-sm text-muted-foreground leading-relaxed max-w-2xl line-clamp-6">
@@ -113,15 +142,20 @@ export function PersonTmdbRedirectPage() {
interface TmdbFilmographySectionProps {
filmography: { cast: TmdbFilmographyItem[]; crew: TmdbFilmographyItem[] };
libraryMap: Map<number, import('@/types').Entry>;
libraryMap: Map<number, import("@/types").Entry>;
libraryLoaded: boolean;
}
function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: TmdbFilmographySectionProps) {
function TmdbFilmographySection({
filmography,
libraryMap,
libraryLoaded,
}: TmdbFilmographySectionProps) {
const [libraryPage, setLibraryPage] = useState(0);
const [otherPage, setOtherPage] = useState(0);
const PAGE_SIZE = 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';
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 (!libraryLoaded) {
return (
@@ -138,7 +172,9 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
const allCredits = [
...(filmography.cast ?? []),
...(filmography.crew?.filter((c) => c.job === 'Director' || c.department === 'Directing') ?? []),
...(filmography.crew?.filter(
(c) => c.job === "Director" || c.department === "Directing",
) ?? []),
];
const seenIds = new Set<number>();
const deduped = allCredits.filter((c) => {
@@ -147,20 +183,29 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
return true;
});
const tmdbIdToLibraryEntry = new Map<number, import('@/types').Entry>();
const tmdbIdToLibraryEntry = new Map<number, import("@/types").Entry>();
for (const entry of libraryMap.values()) {
if (entry.entryIds?.tmdb_id != null) {
tmdbIdToLibraryEntry.set(Number(entry.entryIds.tmdb_id), entry);
}
}
const sorted = [...deduped].sort((a, b) => (b.popularity ?? 0) - (a.popularity ?? 0));
const sorted = [...deduped].sort(
(a, b) => (b.popularity ?? 0) - (a.popularity ?? 0),
);
const libraryCredits = sorted.filter((c) => tmdbIdToLibraryEntry.has(c.id));
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';
return (
lower === "self" ||
lower.startsWith("self -") ||
lower.startsWith("self (") ||
lower === "themselves" ||
lower === "himself" ||
lower === "herself"
);
};
const otherCredits = sorted
.filter((c) => !tmdbIdToLibraryEntry.has(c.id))
@@ -168,8 +213,12 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
const aSelf = isSelfRole(a.character) ? 1 : 0;
const bSelf = isSelfRole(b.character) ? 1 : 0;
if (aSelf !== bSelf) return aSelf - bSelf;
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();
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;
});
@@ -182,8 +231,14 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
);
}
const librarySlice = libraryCredits.slice(libraryPage * PAGE_SIZE, (libraryPage + 1) * PAGE_SIZE);
const otherSlice = otherCredits.slice(otherPage * PAGE_SIZE, (otherPage + 1) * PAGE_SIZE);
const librarySlice = libraryCredits.slice(
libraryPage * PAGE_SIZE,
(libraryPage + 1) * PAGE_SIZE,
);
const otherSlice = otherCredits.slice(
otherPage * PAGE_SIZE,
(otherPage + 1) * PAGE_SIZE,
);
const libraryTotalPages = Math.ceil(libraryCredits.length / PAGE_SIZE);
const otherTotalPages = Math.ceil(otherCredits.length / PAGE_SIZE);
@@ -199,17 +254,25 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
</h3>
{libraryTotalPages > 1 && (
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" className="h-7 w-7"
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={libraryPage === 0}
onClick={() => setLibraryPage((p) => p - 1)}>
onClick={() => setLibraryPage((p) => p - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="text-xs text-muted-foreground tabular-nums">
{libraryPage + 1}/{libraryTotalPages}
</span>
<Button variant="ghost" size="icon" className="h-7 w-7"
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={libraryPage === libraryTotalPages - 1}
onClick={() => setLibraryPage((p) => p + 1)}>
onClick={() => setLibraryPage((p) => p + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
@@ -222,7 +285,9 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
<div key={credit.id} className="space-y-1">
<EntryCard entry={entry} />
{credit.character && (
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">{credit.character}</p>
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">
{credit.character}
</p>
)}
</div>
);
@@ -239,17 +304,25 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
</h3>
{otherTotalPages > 1 && (
<div className="flex items-center gap-1">
<Button variant="ghost" size="icon" className="h-7 w-7"
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={otherPage === 0}
onClick={() => setOtherPage((p) => p - 1)}>
onClick={() => setOtherPage((p) => p - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="text-xs text-muted-foreground tabular-nums">
{otherPage + 1}/{otherTotalPages}
</span>
<Button variant="ghost" size="icon" className="h-7 w-7"
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
disabled={otherPage === otherTotalPages - 1}
onClick={() => setOtherPage((p) => p + 1)}>
onClick={() => setOtherPage((p) => p + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
@@ -266,7 +339,7 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
release_date: credit.release_date,
first_air_date: credit.first_air_date,
media_type: credit.media_type,
overview: '',
overview: "",
vote_average: 0,
vote_count: 0,
genre_ids: [],
@@ -276,7 +349,9 @@ function TmdbFilmographySection({ filmography, libraryMap, libraryLoaded }: Tmdb
<div key={credit.id} className="space-y-1">
<EntryCard tmdbEntry={tmdbEntry} />
{credit.character && (
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">{credit.character}</p>
<p className="text-xs text-muted-foreground text-center line-clamp-1 px-1">
{credit.character}
</p>
)}
</div>
);
+27 -15
View File
@@ -1,16 +1,16 @@
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';
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 initialQuery = searchParams.get("q") || "";
const [searchInput, setSearchInput] = useState(initialQuery);
const [debouncedQuery, setDebouncedQuery] = useState(initialQuery);
const debounceRef = useRef<ReturnType<typeof setTimeout>>();
@@ -39,8 +39,10 @@ export function SearchPage() {
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 searchEntries =
searchResults.data?.pages.flatMap((p) => p.results) ?? [];
const searchPeople =
peopleResults.data?.pages.flatMap((p) => p.results) ?? [];
const isSearching = debouncedQuery.length > 0;
@@ -73,16 +75,26 @@ export function SearchPage() {
>
<Avatar className="h-7 w-7">
<AvatarImage
src={person.profile_path ? getTmdbImageUrl(person.profile_path, 'w92') : undefined}
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)}
{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>
<span className="text-xs text-muted-foreground">
{person.known_for_department}
</span>
)}
</Link>
))}
+43 -28
View File
@@ -1,19 +1,24 @@
import { useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { useSeason, useSeasonEpisodes } from '@/hooks/useSeasons';
import { useEntry, useEntrySeasons } from '@/hooks/useEntries';
import { useLibraryStore } from '@/stores/useLibraryStore';
import { EpisodeSeenEditDialog } from '@/components/dialogs/EpisodeSeenEditDialog';
import { MarkSeasonWatchedDialog } from '@/components/dialogs/MarkSeasonWatchedDialog';
import { StreamingDialog } from '@/components/streaming/StreamingDialog';
import { useStreamingStore } from '@/stores/useStreamingStore';
import { Skeleton } from '@/components/ui/skeleton';
import { Progress } from '@/components/ui/progress';
import { Button } from '@/components/ui/button';
import { Eye, CheckCircle2, ListChecks, PlayCircle } from 'lucide-react';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { getTmdbPosterUrl, getYear, formatDate } from '@/lib/media-utils';
import type { Episode, EpisodeSeen } from '@/types';
import { useState } from "react";
import { useParams, Link } from "react-router-dom";
import { useSeason, useSeasonEpisodes } from "@/hooks/useSeasons";
import { useEntry, useEntrySeasons } from "@/hooks/useEntries";
import { useLibraryStore } from "@/stores/useLibraryStore";
import { EpisodeSeenEditDialog } from "@/components/dialogs/EpisodeSeenEditDialog";
import { MarkSeasonWatchedDialog } from "@/components/dialogs/MarkSeasonWatchedDialog";
import { StreamingDialog } from "@/components/streaming/StreamingDialog";
import { useStreamingStore } from "@/stores/useStreamingStore";
import { Skeleton } from "@/components/ui/skeleton";
import { Progress } from "@/components/ui/progress";
import { Button } from "@/components/ui/button";
import { Eye, CheckCircle2, ListChecks, PlayCircle } from "lucide-react";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { getTmdbPosterUrl, getYear, formatDate } from "@/lib/media-utils";
import type { Episode, EpisodeSeen } from "@/types";
export function SeasonPage() {
const { entryId, seasonId } = useParams<{
@@ -24,7 +29,9 @@ export function SeasonPage() {
const { data: episodes = [] } = useSeasonEpisodes(parseInt(seasonId!, 10));
const { data: entry } = useEntry(parseInt(entryId!, 10));
const { data: entrySeasons } = useEntrySeasons(parseInt(entryId!, 10));
const entryTitle = entry?.title ?? useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title;
const entryTitle =
entry?.title ??
useLibraryStore.getState().entries.get(parseInt(entryId!, 10))?.title;
const { initialize, play } = useStreamingStore();
const [dialogEpisode, setDialogEpisode] = useState<Episode | null>(null);
const [showMarkAllDialog, setShowMarkAllDialog] = useState(false);
@@ -34,7 +41,7 @@ export function SeasonPage() {
if (!entry?.entryIds?.tmdb_id) return;
initialize();
play({
type: 'tv',
type: "tv",
tmdbId: entry.entryIds.tmdb_id,
imdbId: entry.entryIds?.imdb_id || undefined,
season,
@@ -60,8 +67,7 @@ export function SeasonPage() {
const watchedCount = episodes.filter(
(ep: Episode) =>
ep.date_first_seen ||
(ep.episodeSeens && ep.episodeSeens.length > 0)
ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0),
).length;
const totalEpisodes = episodes.length;
const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0;
@@ -74,16 +80,18 @@ export function SeasonPage() {
to={`/entry/${entryId}`}
className="hover:text-foreground transition-colors truncate max-w-50"
>
{entryTitle || 'Entry'}
{entryTitle || "Entry"}
</Link>
<span>/</span>
<span className="text-foreground font-medium">Season {season.season_number}</span>
<span className="text-foreground font-medium">
Season {season.season_number}
</span>
</div>
{/* Header */}
<div className="flex flex-col gap-4 sm:flex-row sm:gap-6">
<img
src={getTmdbPosterUrl(season.poster_path, 'w185')}
src={getTmdbPosterUrl(season.poster_path, "w185")}
alt={season.name}
className="h-40 w-28 shrink-0 rounded-lg object-cover shadow-lg self-center sm:self-start sm:h-56 sm:w-36"
/>
@@ -137,7 +145,9 @@ export function SeasonPage() {
const isWatched =
!!episode.date_first_seen ||
(episode.episodeSeens && episode.episodeSeens.length > 0);
const seenDates = (episode.episodeSeens ?? []).map((s: EpisodeSeen) => s.date_seen);
const seenDates = (episode.episodeSeens ?? []).map(
(s: EpisodeSeen) => s.date_seen,
);
return (
<Link
@@ -152,12 +162,15 @@ export function SeasonPage() {
ev.preventDefault();
ev.stopPropagation();
if (!entry?.entryIds?.tmdb_id) return;
handleWatchEpisode(season.season_number, episode.episode_number);
handleWatchEpisode(
season.season_number,
episode.episode_number,
);
}}
>
{episode.still_path ? (
<img
src={getTmdbPosterUrl(episode.still_path, 'w300')}
src={getTmdbPosterUrl(episode.still_path, "w300")}
alt={episode.name}
className="h-full w-full object-cover transition-[filter] group-hover/thumb:brightness-50"
loading="lazy"
@@ -229,7 +242,7 @@ export function SeasonPage() {
{/* Watch button — always clickable to add another seen record */}
<Button
size="icon"
variant={isWatched ? 'secondary' : 'outline'}
variant={isWatched ? "secondary" : "outline"}
className="h-8 w-8 shrink-0 self-center"
onClick={(ev) => {
ev.preventDefault();
@@ -249,7 +262,9 @@ export function SeasonPage() {
{dialogEpisode && (
<EpisodeSeenEditDialog
open={!!dialogEpisode}
onOpenChange={(open) => { if (!open) setDialogEpisode(null); }}
onOpenChange={(open) => {
if (!open) setDialogEpisode(null);
}}
mode="create"
episodeId={dialogEpisode.id}
entryId={parseInt(entryId!, 10)}