From ab20a5e64f5a28419bca1edab70e13a8221ff215 Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Thu, 2 Apr 2026 03:29:54 +0100 Subject: [PATCH] feat: multi-page improvements, bug fixes, and new features MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Library: - Exclude hidden entries from all/movies/tv/favorites tabs (only show in hidden tab) Entry Details: - Move favorite, mark watched, and more actions to top-right as icon-only buttons with tooltips - Fix season card play button — marks next unwatched episode as seen Seasons Page: - Fix episode watch button (was a TODO stub, now calls createEpisodeSeen) Episode Page: - Fix UI not updating after deleting the last watch record — invalidate season episodes query on delete Dashboard: - Fix Top Genres 404 — was calling non-existent GET /statistics, now uses /statistics/watch-time - Fix TopGenresChart genre counting (Genre objects were wrongly cast as strings) - Add LibraryGrowthChart (cumulative titles added over time) - Add MediaTypeChart (Movies vs TV Series donut chart) Home Page: - Add TrendingSlider hero at top of page with auto-advance, dots, and prev/next nav - Fix slider prev/next buttons (stable callbacks via ref, plain buttons, reactive library state) - Add debounce (400ms) to search input - Add Top Rated section (movies & TV) - Add Upcoming section (movies) - Replace inline "More" expand with link to /discover/:category Discover Page (new): - Full-page TMDB browser per category (trending/popular/top-rated/upcoming) - Movie/TV tab toggle - IntersectionObserver infinite scroll Calendar: - Fix large season numbers — use season.season_number instead of season_id (DB primary key) Backend: - Add fetchTopRated() and fetchUpcoming() to tmdbService - Add GET /entries/tmdb/top-rated/:type and /entries/tmdb/upcoming/movie routes --- backend/controllers/entryController.js | 17 ++ backend/routes/entry.routes.js | 2 + backend/services/tmdbService.js | 26 +++ react_frontend/src/api/statistics.ts | 8 +- react_frontend/src/api/tmdb.ts | 21 +++ .../dashboard/LibraryGrowthChart.tsx | 124 ++++++++++++++ .../components/dashboard/MediaTypeChart.tsx | 90 +++++++++++ .../components/dashboard/TopGenresChart.tsx | 6 +- .../components/entries/SeasonsContainer.tsx | 16 +- .../src/components/entries/TrendingGrid.tsx | 19 +-- .../src/components/entries/TrendingSlider.tsx | 151 ++++++++++++++++++ react_frontend/src/hooks/useEpisodeSeen.ts | 10 ++ react_frontend/src/hooks/useStatistics.ts | 4 +- react_frontend/src/hooks/useTmdb.ts | 30 ++++ react_frontend/src/pages/CalendarPage.tsx | 5 +- react_frontend/src/pages/DashboardPage.tsx | 12 +- react_frontend/src/pages/DiscoverPage.tsx | 132 +++++++++++++++ react_frontend/src/pages/EntryDetailsPage.tsx | 147 +++++++++-------- react_frontend/src/pages/EpisodePage.tsx | 2 +- react_frontend/src/pages/HomePage.tsx | 72 +++++++-- react_frontend/src/pages/LibraryPage.tsx | 8 +- react_frontend/src/pages/SeasonPage.tsx | 11 +- react_frontend/src/router.tsx | 11 ++ 23 files changed, 820 insertions(+), 104 deletions(-) create mode 100644 react_frontend/src/components/dashboard/LibraryGrowthChart.tsx create mode 100644 react_frontend/src/components/dashboard/MediaTypeChart.tsx create mode 100644 react_frontend/src/components/entries/TrendingSlider.tsx create mode 100644 react_frontend/src/pages/DiscoverPage.tsx diff --git a/backend/controllers/entryController.js b/backend/controllers/entryController.js index a82147e..95a9a86 100644 --- a/backend/controllers/entryController.js +++ b/backend/controllers/entryController.js @@ -146,6 +146,23 @@ class EntryController { if (!data) return res.status(500).json({ message: 'Failed to search TMDB' }); res.status(200).json(data); }); + + // * GET - TMDB TOP RATED + getTmdbTopRated = asyncWrapper(async (req, res) => { + const { type } = req.params; + const { page } = req.query; + const data = await tmdbService.fetchTopRated(type, page || 1); + if (!data) return res.status(500).json({ message: 'Failed to fetch top rated data' }); + res.status(200).json(data); + }); + + // * GET - TMDB UPCOMING + getTmdbUpcoming = asyncWrapper(async (req, res) => { + const { page } = req.query; + const data = await tmdbService.fetchUpcoming(page || 1); + if (!data) return res.status(500).json({ message: 'Failed to fetch upcoming data' }); + res.status(200).json(data); + }); } module.exports = new EntryController(); diff --git a/backend/routes/entry.routes.js b/backend/routes/entry.routes.js index 19fd6bc..9b93051 100644 --- a/backend/routes/entry.routes.js +++ b/backend/routes/entry.routes.js @@ -14,6 +14,8 @@ const mediaOptimizerService = require('../services/mediaOptimizerService'); // ! TMDB PROXY ROUTES (must be before /:id to avoid matching) entryRouter.get('/tmdb/trending/:type', entryController.getTmdbTrending); entryRouter.get('/tmdb/popular/:type', entryController.getTmdbPopular); +entryRouter.get('/tmdb/top-rated/:type', entryController.getTmdbTopRated); +entryRouter.get('/tmdb/upcoming/movie', entryController.getTmdbUpcoming); entryRouter.get('/tmdb/search', entryController.getTmdbSearch); entryRouter.get('/sync-series', entryController.syncSeries); diff --git a/backend/services/tmdbService.js b/backend/services/tmdbService.js index eb96a00..3e3e32d 100644 --- a/backend/services/tmdbService.js +++ b/backend/services/tmdbService.js @@ -173,6 +173,30 @@ async function fetchPopular(type, page = 1) { } } +async function fetchTopRated(type, page = 1) { + try { + let url = `${TMDB_APIURL}${type}/top_rated?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`; + logToFile(`Fetching Top Rated ${type} From: ${url}`); + const response = await axios.get(url); + return response.data; + } catch (error) { + console.log(`Error fetching top rated ${type}.`, error); + return null; + } +} + +async function fetchUpcoming(page = 1) { + try { + let url = `${TMDB_APIURL}movie/upcoming?api_key=${TMDB_APIKEY}&language=en-US&page=${page}`; + logToFile(`Fetching Upcoming Movies From: ${url}`); + const response = await axios.get(url); + return response.data; + } catch (error) { + console.log('Error fetching upcoming movies.', error); + return null; + } +} + async function searchMulti(query, page = 1) { try { let url = `${TMDB_APIURL}search/multi?api_key=${TMDB_APIKEY}&language=en-US&query=${encodeURIComponent(query)}&page=${page}`; @@ -231,6 +255,8 @@ module.exports = { fetchPersonCombinedCredits, fetchTrending, fetchPopular, + fetchTopRated, + fetchUpcoming, searchMulti, searchPeople, fetchPopularPeople, diff --git a/react_frontend/src/api/statistics.ts b/react_frontend/src/api/statistics.ts index 00c6505..e075b21 100644 --- a/react_frontend/src/api/statistics.ts +++ b/react_frontend/src/api/statistics.ts @@ -30,8 +30,14 @@ export interface WatchdayDistribution { movies: WatchdayItem[]; } +export interface AllTimeWatchTime { + series: string | null; + movies: string | null; +} + export const statisticsApi = { - get: () => api.get('/statistics').then((r) => r.data), + getAllTimeWatchTime: () => + api.get('/statistics/watch-time').then((r) => r.data), getYearlyWatchCount: (year: number) => api.get(`/statistics/watch-count/year/${year}`).then((r) => r.data), getYearlyWatchTime: (year: number) => diff --git a/react_frontend/src/api/tmdb.ts b/react_frontend/src/api/tmdb.ts index 5ab428b..2860536 100644 --- a/react_frontend/src/api/tmdb.ts +++ b/react_frontend/src/api/tmdb.ts @@ -30,6 +30,27 @@ export const tmdbApi = { }) .then((r) => r.data), + getTopRatedMovies: (page = 1) => + api + .get>('/entries/tmdb/top-rated/movie', { + params: { page }, + }) + .then((r) => r.data), + + getTopRatedTv: (page = 1) => + api + .get>('/entries/tmdb/top-rated/tv', { + params: { page }, + }) + .then((r) => r.data), + + getUpcomingMovies: (page = 1) => + api + .get>('/entries/tmdb/upcoming/movie', { + params: { page }, + }) + .then((r) => r.data), + search: (query: string, page = 1) => api .get>('/entries/tmdb/search', { diff --git a/react_frontend/src/components/dashboard/LibraryGrowthChart.tsx b/react_frontend/src/components/dashboard/LibraryGrowthChart.tsx new file mode 100644 index 0000000..b985356 --- /dev/null +++ b/react_frontend/src/components/dashboard/LibraryGrowthChart.tsx @@ -0,0 +1,124 @@ +import { useMemo, useState } from 'react'; +import { + AreaChart, + Area, + XAxis, + YAxis, + CartesianGrid, + Tooltip, + ResponsiveContainer, +} from 'recharts'; +import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; +import { useLibraryEntries } from '@/stores/useLibraryStore'; + +const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +interface CustomTooltipProps { + active?: boolean; + payload?: { value: number; payload: { month: string; count: number; cumulative: number } }[]; +} + +function CustomTooltip({ active, payload }: CustomTooltipProps) { + if (!active || !payload?.length) return null; + const d = payload[0].payload; + return ( +
+

{d.month}

+

+{d.count} added

+

{d.cumulative} total

+
+ ); +} + +export function LibraryGrowthChart() { + const allEntries = useLibraryEntries(); + const currentYear = new Date().getFullYear(); + const [year, setYear] = useState(currentYear); + + const years = useMemo(() => { + const set = new Set(); + allEntries.forEach((e) => { + if (e.createdAt) set.add(new Date(e.createdAt).getFullYear()); + }); + return Array.from(set).sort((a, b) => b - a); + }, [allEntries]); + + const chartData = useMemo(() => { + const library = allEntries.filter((e) => !e.watchlist); + // Count entries added before this year for initial cumulative + const beforeYear = library.filter( + (e) => e.createdAt && new Date(e.createdAt).getFullYear() < year + ).length; + + const monthlyCounts = new Array(12).fill(0); + library.forEach((e) => { + if (!e.createdAt) return; + const d = new Date(e.createdAt); + if (d.getFullYear() === year) { + monthlyCounts[d.getMonth()]++; + } + }); + + let cumulative = beforeYear; + return MONTH_LABELS.map((label, i) => { + cumulative += monthlyCounts[i]; + return { month: label, count: monthlyCounts[i], cumulative }; + }); + }, [allEntries, year]); + + return ( + + +
+
+ Library Growth + + Titles added to your library over time + +
+ +
+
+ + + + + + + + + + + + + } /> + + + + +
+ ); +} diff --git a/react_frontend/src/components/dashboard/MediaTypeChart.tsx b/react_frontend/src/components/dashboard/MediaTypeChart.tsx new file mode 100644 index 0000000..3fe4185 --- /dev/null +++ b/react_frontend/src/components/dashboard/MediaTypeChart.tsx @@ -0,0 +1,90 @@ +import { useMemo } from 'react'; +import { + PieChart, + Pie, + Cell, + ResponsiveContainer, + Tooltip, + Legend, +} from 'recharts'; +import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; +import { useLibraryEntries } from '@/stores/useLibraryStore'; + +const COLORS = ['var(--color-chart-1)', 'var(--color-chart-2)']; + +interface CustomTooltipProps { + active?: boolean; + payload?: { name: string; value: number }[]; +} + +function CustomTooltip({ active, payload }: CustomTooltipProps) { + if (!active || !payload?.length) return null; + const { name, value } = payload[0]; + return ( +
+

{name}

+

{value} titles

+
+ ); +} + +export function MediaTypeChart() { + const allEntries = useLibraryEntries(); + + const chartData = useMemo(() => { + const library = allEntries.filter((e) => !e.watchlist); + const movies = library.filter((e) => !e.is_tvseries).length; + const tv = library.filter((e) => e.is_tvseries).length; + return [ + { name: 'Movies', value: movies }, + { name: 'TV Series', value: tv }, + ]; + }, [allEntries]); + + const total = chartData.reduce((s, d) => s + d.value, 0); + + return ( + + + Movies vs TV Series + + {total} titles in your library + + + + + + + {chartData.map((_, index) => ( + + ))} + + } /> + ( + {value} + )} + /> + + + + + ); +} diff --git a/react_frontend/src/components/dashboard/TopGenresChart.tsx b/react_frontend/src/components/dashboard/TopGenresChart.tsx index 8eb4524..3687e98 100644 --- a/react_frontend/src/components/dashboard/TopGenresChart.tsx +++ b/react_frontend/src/components/dashboard/TopGenresChart.tsx @@ -30,8 +30,10 @@ function buildGenreData(entries: Entry[]) { const counts: Record = {}; for (const entry of entries) { if (!entry.genres) continue; - for (const genre of entry.genres as unknown as string[]) { - counts[genre] = (counts[genre] ?? 0) + 1; + for (const genre of entry.genres) { + const name = typeof genre === 'string' ? genre : genre.name; + if (!name) continue; + counts[name] = (counts[name] ?? 0) + 1; } } return Object.entries(counts) diff --git a/react_frontend/src/components/entries/SeasonsContainer.tsx b/react_frontend/src/components/entries/SeasonsContainer.tsx index 6368322..ba466da 100644 --- a/react_frontend/src/components/entries/SeasonsContainer.tsx +++ b/react_frontend/src/components/entries/SeasonsContainer.tsx @@ -4,6 +4,7 @@ import { ChevronDown, ChevronUp, Play } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Progress } from '@/components/ui/progress'; import { getYear, getTmdbPosterUrl } from '@/lib/media-utils'; +import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen'; import type { Season } from '@/types'; interface SeasonsContainerProps { @@ -64,6 +65,7 @@ function SeasonItem({ season: Season; entryId: number; }) { + const createEpisodeSeen = useCreateEpisodeSeen(); const watchedCount = season.episodes?.filter( (ep) => ep.date_first_seen || (ep.episodeSeens && ep.episodeSeens.length > 0) @@ -71,6 +73,11 @@ function SeasonItem({ const totalEpisodes = season.episode_count || season.episodes?.length || 0; const progress = totalEpisodes > 0 ? (watchedCount / totalEpisodes) * 100 : 0; + const nextUnwatched = season.episodes + ?.slice() + .sort((a, b) => a.episode_number - b.episode_number) + .find((ep) => !ep.date_first_seen && (!ep.episodeSeens || ep.episodeSeens.length === 0)); + return ( {/* Quick watch button */} - {watchedCount < totalEpisodes && ( + {nextUnwatched && ( diff --git a/react_frontend/src/components/entries/TrendingGrid.tsx b/react_frontend/src/components/entries/TrendingGrid.tsx index ce3959a..77dbb67 100644 --- a/react_frontend/src/components/entries/TrendingGrid.tsx +++ b/react_frontend/src/components/entries/TrendingGrid.tsx @@ -11,7 +11,8 @@ interface TrendingGridProps { movieEntries: TmdbEntry[]; tvEntries: TmdbEntry[]; isLoading?: boolean; - moreLink: string; + /** Route segment used for the "More" link, e.g. "trending" → /discover/trending */ + category: string; } export function TrendingGrid({ @@ -19,12 +20,10 @@ export function TrendingGrid({ movieEntries, tvEntries, isLoading, - moreLink, + category, }: TrendingGridProps) { const [activeTab, setActiveTab] = useState<'movie' | 'tv'>('movie'); const entries = activeTab === 'movie' ? movieEntries : tvEntries; - - // Limit to 2 rows (14 items for a 7-column grid) const displayEntries = entries.slice(0, 14); return ( @@ -45,11 +44,13 @@ export function TrendingGrid({ - + + More + + diff --git a/react_frontend/src/components/entries/TrendingSlider.tsx b/react_frontend/src/components/entries/TrendingSlider.tsx new file mode 100644 index 0000000..a5aeccb --- /dev/null +++ b/react_frontend/src/components/entries/TrendingSlider.tsx @@ -0,0 +1,151 @@ +import { useState, useEffect, useCallback, useRef } from 'react'; +import { Link } from 'react-router-dom'; +import { ChevronLeft, ChevronRight, Star } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { useCreateEntry } from '@/hooks/useEntries'; +import { useLibraryStore } from '@/stores/useLibraryStore'; +import type { TmdbEntry } from '@/types'; + +interface TrendingSliderProps { + entries: TmdbEntry[]; + isLoading?: boolean; +} + +export function TrendingSlider({ entries, isLoading }: TrendingSliderProps) { + const [currentIndex, setCurrentIndex] = useState(0); + const createEntry = useCreateEntry(); + const display = entries.slice(0, 10); + const countRef = useRef(display.length); + countRef.current = display.length; + + const next = useCallback(() => { + if (countRef.current === 0) return; + setCurrentIndex((i) => (i + 1) % countRef.current); + }, []); + + const prev = useCallback(() => { + if (countRef.current === 0) return; + setCurrentIndex((i) => (i - 1 + countRef.current) % countRef.current); + }, []); + + // Reset index when entries change so it stays in range + useEffect(() => { + setCurrentIndex(0); + }, [entries.length]); + + useEffect(() => { + if (display.length === 0) return; + const timer = setInterval(next, 6000); + return () => clearInterval(timer); + }, [next, display.length]); + + if (isLoading || display.length === 0) { + return ( +
+ ); + } + + const safeIndex = currentIndex < display.length ? currentIndex : 0; + const item = display[safeIndex]; + const title = item.title || item.name || 'Untitled'; + const backdropUrl = item.backdrop_path + ? `https://image.tmdb.org/t/p/w1280${item.backdrop_path}` + : null; + const isTv = item.media_type === 'tv' || !!item.name; + + const libraryEntries = useLibraryStore((s) => s.entries); + const matchedEntry = Array.from(libraryEntries.values()).find( + (e) => e.entryIds?.tmdb_id === item.id + ); + const isInLibrary = !!matchedEntry; + + return ( +
+ {/* Backdrop */} + {backdropUrl ? ( + + ) : ( +
+ )} +
+ + {/* Nav arrows */} + + + + {/* Content overlay */} +
+
+
+ + {isTv ? 'TV Series' : 'Movie'} + + {item.vote_average > 0 && ( + + + {item.vote_average.toFixed(1)} + + )} +
+

+ {title} +

+ {item.overview && ( +

+ {item.overview} +

+ )} +
+ {isInLibrary && matchedEntry ? ( + + + + ) : ( + + )} +
+
+
+ + {/* Dots */} +
+ {display.map((_, i) => ( +
+
+ ); +} diff --git a/react_frontend/src/hooks/useEpisodeSeen.ts b/react_frontend/src/hooks/useEpisodeSeen.ts index 58c4e8e..223273c 100644 --- a/react_frontend/src/hooks/useEpisodeSeen.ts +++ b/react_frontend/src/hooks/useEpisodeSeen.ts @@ -2,6 +2,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { toast } from 'sonner'; import { episodeSeenApi } from '@/api/episode-seen'; import { entryKeys } from './useEntries'; +import { seasonKeys } from './useSeasons'; export const episodeSeenKeys = { all: ['episode-seen'] as const, @@ -83,6 +84,7 @@ export function useDeleteEpisodeSeen() { id: number; entryId: number; episodeId: number; + seasonId?: number; }) => episodeSeenApi.delete(id), onSuccess: (_data, variables) => { queryClient.invalidateQueries({ @@ -91,6 +93,14 @@ export function useDeleteEpisodeSeen() { queryClient.invalidateQueries({ queryKey: entryKeys.detail(variables.entryId), }); + queryClient.invalidateQueries({ + queryKey: entryKeys.seasons(variables.entryId), + }); + if (variables.seasonId) { + queryClient.invalidateQueries({ + queryKey: seasonKeys.episodes(variables.seasonId), + }); + } toast.success('Episode watch record removed'); }, onError: () => { diff --git a/react_frontend/src/hooks/useStatistics.ts b/react_frontend/src/hooks/useStatistics.ts index a7aa251..511842e 100644 --- a/react_frontend/src/hooks/useStatistics.ts +++ b/react_frontend/src/hooks/useStatistics.ts @@ -3,8 +3,8 @@ import { statisticsApi } from '@/api/statistics'; export function useStatistics() { return useQuery({ - queryKey: ['statistics'], - queryFn: statisticsApi.get, + queryKey: ['statistics', 'watch-time-all'], + queryFn: statisticsApi.getAllTimeWatchTime, }); } diff --git a/react_frontend/src/hooks/useTmdb.ts b/react_frontend/src/hooks/useTmdb.ts index acfaf6b..ebb4019 100644 --- a/react_frontend/src/hooks/useTmdb.ts +++ b/react_frontend/src/hooks/useTmdb.ts @@ -41,6 +41,36 @@ export function useTrendingTv() { }); } +export function useTopRatedMovies() { + return useInfiniteQuery({ + queryKey: ['tmdb', 'top-rated', 'movie'], + queryFn: ({ pageParam }) => tmdbApi.getTopRatedMovies(pageParam), + initialPageParam: 1, + getNextPageParam: (lastPage) => + lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined, + }); +} + +export function useTopRatedTv() { + return useInfiniteQuery({ + queryKey: ['tmdb', 'top-rated', 'tv'], + queryFn: ({ pageParam }) => tmdbApi.getTopRatedTv(pageParam), + initialPageParam: 1, + getNextPageParam: (lastPage) => + lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined, + }); +} + +export function useUpcomingMovies() { + return useInfiniteQuery({ + queryKey: ['tmdb', 'upcoming', 'movie'], + queryFn: ({ pageParam }) => tmdbApi.getUpcomingMovies(pageParam), + initialPageParam: 1, + getNextPageParam: (lastPage) => + lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined, + }); +} + export function useTmdbSearch(query: string) { return useInfiniteQuery({ queryKey: ['tmdb', 'search', query], diff --git a/react_frontend/src/pages/CalendarPage.tsx b/react_frontend/src/pages/CalendarPage.tsx index 9de9827..93fd761 100644 --- a/react_frontend/src/pages/CalendarPage.tsx +++ b/react_frontend/src/pages/CalendarPage.tsx @@ -130,8 +130,11 @@ function EpisodeCalendarItem({ episode }: { episode: Episode }) { const entryId = entry?.id; const entryTitle = entry?.title ?? ''; const seasonId = episode.season_id; + const seasonNumber = episode.season?.season_number ?? null; - const seasonLabel = `S${String(seasonId).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 = episode.still_path diff --git a/react_frontend/src/pages/DashboardPage.tsx b/react_frontend/src/pages/DashboardPage.tsx index 1688c92..e32153b 100644 --- a/react_frontend/src/pages/DashboardPage.tsx +++ b/react_frontend/src/pages/DashboardPage.tsx @@ -12,6 +12,8 @@ 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(); @@ -51,8 +53,8 @@ export function DashboardPage() { }, { title: 'Watch Time', - value: stats?.totalWatchTime - ? formatRuntime(stats.totalWatchTime) + value: stats + ? formatRuntime((parseInt(stats.series || '0') || 0) + (parseInt(stats.movies || '0') || 0)) : '0h', icon: Clock, color: 'text-orange-500', @@ -91,7 +93,11 @@ export function DashboardPage() {
- +
+ + +
+ {/* Recently Watched */}
diff --git a/react_frontend/src/pages/DiscoverPage.tsx b/react_frontend/src/pages/DiscoverPage.tsx new file mode 100644 index 0000000..f054785 --- /dev/null +++ b/react_frontend/src/pages/DiscoverPage.tsx @@ -0,0 +1,132 @@ +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 = { + trending: 'Trending', + popular: 'Popular', + 'top-rated': 'Top Rated', + upcoming: 'Upcoming', +}; + +type MediaTab = 'movie' | 'tv'; + +function useCategoryQuery(category: string, mediaType: MediaTab) { + return useInfiniteQuery>({ + queryKey: ['tmdb', category, mediaType], + queryFn: ({ pageParam }) => { + const page = pageParam as number; + switch (category) { + case 'trending': + return mediaType === 'movie' + ? tmdbApi.getTrendingMovies(page) + : tmdbApi.getTrendingTv(page); + case 'popular': + return mediaType === 'movie' + ? tmdbApi.getPopularMovies(page) + : tmdbApi.getPopularTv(page); + case 'top-rated': + return mediaType === 'movie' + ? tmdbApi.getTopRatedMovies(page) + : tmdbApi.getTopRatedTv(page); + case 'upcoming': + return tmdbApi.getUpcomingMovies(page); + default: + return tmdbApi.getPopularMovies(page); + } + }, + initialPageParam: 1, + getNextPageParam: (lastPage) => + lastPage.page < lastPage.total_pages ? lastPage.page + 1 : undefined, + }); +} + +export function DiscoverPage() { + const { category = 'trending' } = useParams<{ category: string }>(); + const [mediaType, setMediaType] = useState('movie'); + const sentinelRef = useRef(null); + + useLibrary(); + + 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) { + query.fetchNextPage(); + } + }, + [query.hasNextPage, query.isFetchingNextPage, query.fetchNextPage], + ); + + useEffect(() => { + const el = sentinelRef.current; + if (!el) return; + const observer = new IntersectionObserver(handleIntersect, { rootMargin: '400px' }); + observer.observe(el); + return () => observer.disconnect(); + }, [handleIntersect]); + + const title = CATEGORY_LABELS[category] || 'Discover'; + + return ( +
+
+

{title}

+ {!isUpcoming && ( + setMediaType(v as MediaTab)} + > + + + Movies + + + TV Series + + + + )} +
+ + {query.isLoading ? ( +
+ {Array.from({ length: 21 }).map((_, i) => ( + + ))} +
+ ) : entries.length === 0 ? ( +

No results found.

+ ) : ( +
+ {entries.map((entry, index) => ( +
+ +
+ ))} +
+ )} + + {/* Infinite scroll sentinel */} +
+ {query.isFetchingNextPage && ( + + )} +
+
+ ); +} diff --git a/react_frontend/src/pages/EntryDetailsPage.tsx b/react_frontend/src/pages/EntryDetailsPage.tsx index 47031bf..31b823d 100644 --- a/react_frontend/src/pages/EntryDetailsPage.tsx +++ b/react_frontend/src/pages/EntryDetailsPage.tsx @@ -107,80 +107,91 @@ export function EntryDetailsPage() { {/* Main content */}
+ {/* Action buttons — top right */} +
+ + + + + + {e.favorit ? 'Unfavorite' : 'Favorite'} + + + + + + + Mark Watched + + + + + + + + + setShowRatingDialog(true)}> + + Rate this + + + updateEntry.mutate({ id: e.id, data: { hidden: !e.hidden } }) + } + > + + {e.hidden ? 'Unhide' : 'Hide'} + + refreshEntry.mutate(e.id)} disabled={refreshEntry.isPending}> + + {refreshEntry.isPending ? 'Refreshing...' : 'Refresh details'} + + setShowCollectionDialog(true)}> + + Add to collection + + setShowMediaDialog(true)}> + + Manage media + + setShowSettings(true)}> + + Settings + + + +
+ {/* Two-column header: sticky poster | info */} -
- {/* LEFT: Sticky poster + actions */} -
+
+ {/* LEFT: Sticky poster */} +
{e.title} -
- - - - - - - - - - setShowRatingDialog(true)}> - - Rate this - - - updateEntry.mutate({ id: e.id, data: { hidden: !e.hidden } }) - } - > - - {e.hidden ? 'Unhide' : 'Hide'} - - refreshEntry.mutate(e.id)} disabled={refreshEntry.isPending}> - - {refreshEntry.isPending ? 'Refreshing...' : 'Refresh details'} - - setShowCollectionDialog(true)}> - - Add to collection - - setShowMediaDialog(true)}> - - Manage media - - setShowSettings(true)}> - - Settings - - - -
{/* RIGHT: Entry info */} diff --git a/react_frontend/src/pages/EpisodePage.tsx b/react_frontend/src/pages/EpisodePage.tsx index 39a871b..c80741f 100644 --- a/react_frontend/src/pages/EpisodePage.tsx +++ b/react_frontend/src/pages/EpisodePage.tsx @@ -196,7 +196,7 @@ export function EpisodePage() { variant="destructive" onConfirm={() => { if (deleteTarget !== null) { - deleteEpisodeSeen.mutate({ id: deleteTarget, entryId: entryIdNum, episodeId: epId }); + deleteEpisodeSeen.mutate({ id: deleteTarget, entryId: entryIdNum, episodeId: epId, seasonId: parseInt(seasonId!, 10) }); setDeleteTarget(null); } }} diff --git a/react_frontend/src/pages/HomePage.tsx b/react_frontend/src/pages/HomePage.tsx index 9c9cdfa..83e53a5 100644 --- a/react_frontend/src/pages/HomePage.tsx +++ b/react_frontend/src/pages/HomePage.tsx @@ -1,13 +1,35 @@ -import { useTrendingMovies, useTrendingTv, usePopularMovies, usePopularTv, useTmdbSearch } from '@/hooks/useTmdb'; +import { + useTrendingMovies, + useTrendingTv, + usePopularMovies, + usePopularTv, + useTopRatedMovies, + useTopRatedTv, + useUpcomingMovies, + useTmdbSearch, +} from '@/hooks/useTmdb'; import { useLibrary } from '@/hooks/useEntries'; import { TrendingGrid } from '@/components/entries/TrendingGrid'; +import { TrendingSlider } from '@/components/entries/TrendingSlider'; import { Input } from '@/components/ui/input'; -import { useState } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { Search } from 'lucide-react'; import { EntryCard } from '@/components/entries/EntryCard'; export function HomePage() { - const [searchQuery, setSearchQuery] = useState(''); + const [searchInput, setSearchInput] = useState(''); + const [debouncedQuery, setDebouncedQuery] = useState(''); + const debounceRef = useRef>(); + + useEffect(() => { + if (debounceRef.current) clearTimeout(debounceRef.current); + debounceRef.current = setTimeout(() => { + setDebouncedQuery(searchInput); + }, 400); + return () => { + if (debounceRef.current) clearTimeout(debounceRef.current); + }; + }, [searchInput]); // Pre-load library useLibrary(); @@ -16,25 +38,39 @@ export function HomePage() { const trendingTv = useTrendingTv(); const popularMovies = usePopularMovies(); const popularTv = usePopularTv(); - const searchResults = useTmdbSearch(searchQuery); + const topRatedMovies = useTopRatedMovies(); + const topRatedTv = useTopRatedTv(); + const upcomingMovies = useUpcomingMovies(); + const searchResults = useTmdbSearch(debouncedQuery); const trendingMovieEntries = trendingMovies.data?.pages.flatMap((p) => p.results) ?? []; const trendingTvEntries = trendingTv.data?.pages.flatMap((p) => p.results) ?? []; const popularMovieEntries = popularMovies.data?.pages.flatMap((p) => p.results) ?? []; const popularTvEntries = popularTv.data?.pages.flatMap((p) => p.results) ?? []; + const topRatedMovieEntries = topRatedMovies.data?.pages.flatMap((p) => p.results) ?? []; + const topRatedTvEntries = topRatedTv.data?.pages.flatMap((p) => p.results) ?? []; + const upcomingMovieEntries = upcomingMovies.data?.pages.flatMap((p) => p.results) ?? []; const searchEntries = searchResults.data?.pages.flatMap((p) => p.results) ?? []; - const isSearching = searchQuery.length > 0; + const isSearching = debouncedQuery.length > 0; return (
+ {/* Trending Slider Hero */} + {!isSearching && ( + + )} + {/* Search */}
setSearchQuery(e.target.value)} + value={searchInput} + onChange={(e) => setSearchInput(e.target.value)} className="pl-10" />
@@ -42,7 +78,7 @@ export function HomePage() { {isSearching ? (

- Search Results for "{searchQuery}" + Search Results for "{debouncedQuery}"

{searchEntries.length === 0 && !searchResults.isLoading ? (

No results found.

@@ -67,7 +103,7 @@ export function HomePage() { movieEntries={trendingMovieEntries} tvEntries={trendingTvEntries} isLoading={trendingMovies.isLoading || trendingTv.isLoading} - moreLink="/library" + category="trending" /> + + + + )} diff --git a/react_frontend/src/pages/LibraryPage.tsx b/react_frontend/src/pages/LibraryPage.tsx index aff7b34..ce3b080 100644 --- a/react_frontend/src/pages/LibraryPage.tsx +++ b/react_frontend/src/pages/LibraryPage.tsx @@ -80,15 +80,15 @@ export function LibraryPage() { const baseEntries = useMemo(() => { switch (activeTab) { case 'movies': - return allEntries.filter((e) => !e.is_tvseries && !e.watchlist); + return allEntries.filter((e) => !e.is_tvseries && !e.watchlist && !e.hidden); case 'tv': - return allEntries.filter((e) => e.is_tvseries && !e.watchlist); + return allEntries.filter((e) => e.is_tvseries && !e.watchlist && !e.hidden); case 'favorites': - return allEntries.filter((e) => e.favorit && !e.watchlist); + return allEntries.filter((e) => e.favorit && !e.watchlist && !e.hidden); case 'hidden': return allEntries.filter((e) => e.hidden); default: - return allEntries.filter((e) => !e.watchlist); + return allEntries.filter((e) => !e.watchlist && !e.hidden); } }, [activeTab, allEntries]); diff --git a/react_frontend/src/pages/SeasonPage.tsx b/react_frontend/src/pages/SeasonPage.tsx index 6158aff..320cd45 100644 --- a/react_frontend/src/pages/SeasonPage.tsx +++ b/react_frontend/src/pages/SeasonPage.tsx @@ -1,5 +1,6 @@ import { useParams, Link } from 'react-router-dom'; import { useSeason, useSeasonEpisodes } from '@/hooks/useSeasons'; +import { useCreateEpisodeSeen } from '@/hooks/useEpisodeSeen'; import { Skeleton } from '@/components/ui/skeleton'; import { Progress } from '@/components/ui/progress'; import { Badge } from '@/components/ui/badge'; @@ -14,6 +15,7 @@ export function SeasonPage() { }>(); const { data: season, isLoading } = useSeason(parseInt(seasonId!, 10)); const { data: episodes = [] } = useSeasonEpisodes(parseInt(seasonId!, 10)); + const createEpisodeSeen = useCreateEpisodeSeen(); if (isLoading || !season) { return ( @@ -141,8 +143,15 @@ export function SeasonPage() { onClick={(ev) => { ev.preventDefault(); ev.stopPropagation(); - // TODO: Mark episode as watched + if (!isWatched) { + createEpisodeSeen.mutate({ + entry_id: parseInt(entryId!, 10), + episode_id: episode.id, + date_seen: new Date().toISOString(), + }); + } }} + disabled={isWatched || createEpisodeSeen.isPending} > diff --git a/react_frontend/src/router.tsx b/react_frontend/src/router.tsx index 223e09d..5e5a67d 100644 --- a/react_frontend/src/router.tsx +++ b/react_frontend/src/router.tsx @@ -74,6 +74,9 @@ const PersonTmdbRedirectPage = lazy(() => const SettingsPage = lazy(() => import('@/pages/SettingsPage').then((m) => ({ default: m.SettingsPage })) ); +const DiscoverPage = lazy(() => + import('@/pages/DiscoverPage').then((m) => ({ default: m.DiscoverPage })) +); function SuspensePage({ children, fallback }: { children: ReactNode; fallback?: ReactNode }) { return }>{children}; @@ -107,6 +110,14 @@ export const router = createBrowserRouter([ ), }, + { + path: '/discover/:category', + element: ( + }> + + + ), + }, { path: '/watchlist', element: (