feat: add custom hook for managing default season selection in TV series
This commit is contained in:
1 parent
0f5482627a
commit
47a486a3ad
2 files changed
+173
-14
No files matched your search
@@ -11,6 +11,7 @@ import Typography from "@mui/material/Typography";
|
||||
import { green, red, yellow } from "@mui/material/colors";
|
||||
|
||||
import useParallax from "@/utils/hooks/useParallax";
|
||||
import useDefaultSeason from "@/utils/hooks/useDefaultSeason";
|
||||
import { AnimatePresence, motion, useScroll } from "motion/react";
|
||||
|
||||
import { Blurhash } from "react-blurhash";
|
||||
@@ -109,7 +110,6 @@ function SeriesTitlePage() {
|
||||
const result = await getTvShowsApi(api).getSeasons({
|
||||
userId: user?.Id,
|
||||
seriesId: item.data.Id,
|
||||
isSpecialSeason: false,
|
||||
isMissing: false,
|
||||
});
|
||||
return result.data;
|
||||
@@ -124,14 +124,9 @@ function SeriesTitlePage() {
|
||||
});
|
||||
const [backdropImageLoaded, setBackdropImageLoaded] = useState(false);
|
||||
|
||||
const [currentSeason, setCurrentSeason] = useState(() => {
|
||||
const result = sessionStorage.getItem(`season-${item.data?.Id}`);
|
||||
return result ?? 0;
|
||||
});
|
||||
const [currentSeason, setCurrentSeason] = useDefaultSeason(seasons, item.data?.Id);
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentSeason(sessionStorage.getItem(`season-${item.data?.Id}`) ?? 0);
|
||||
}, [item.data?.Id]);
|
||||
const currentSeasonNumber = Number(currentSeason);
|
||||
|
||||
const currentSeasonItem = useQuery({
|
||||
queryKey: ["item", id, "season", currentSeason],
|
||||
@@ -901,13 +896,16 @@ function SeriesTitlePage() {
|
||||
/>
|
||||
)}
|
||||
<TextField
|
||||
value={currentSeason}
|
||||
value={currentSeasonNumber}
|
||||
onChange={(e) => {
|
||||
setCurrentSeason(e.target.value);
|
||||
sessionStorage.setItem(
|
||||
`season-${item.data?.Id}`,
|
||||
e.target.value,
|
||||
);
|
||||
const seasonIndex = Number(e.target.value);
|
||||
if (!isNaN(seasonIndex) && isFinite(seasonIndex)) {
|
||||
setCurrentSeason(seasonIndex);
|
||||
sessionStorage.setItem(
|
||||
`season-${item.data?.Id}`,
|
||||
seasonIndex.toString(),
|
||||
);
|
||||
}
|
||||
}}
|
||||
select
|
||||
SelectProps={{
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
/**
|
||||
* Custom hook for selecting and managing the default season for a TV series.
|
||||
* Handles season selection logic including:
|
||||
* - Restoring previously selected season from sessionStorage
|
||||
* - Auto-selecting the first unwatched regular season (prioritizes regular seasons over specials)
|
||||
* - Only falls back to special seasons if no regular seasons exist
|
||||
* - Properly handles the case where some episodes in special seasons are watched
|
||||
*/
|
||||
// Define a type for Season UserData
|
||||
type SeasonUserData = {
|
||||
Played?: boolean;
|
||||
PlayedPercentage?: number;
|
||||
};
|
||||
|
||||
// Define a type for Season
|
||||
type Season = {
|
||||
Id: string;
|
||||
IndexNumber: number | null;
|
||||
UserData?: SeasonUserData;
|
||||
// Add any other properties you expect from a season item
|
||||
[key: string]: any;
|
||||
};
|
||||
|
||||
function useDefaultSeason(
|
||||
seasons: ReturnType<typeof useQuery>,
|
||||
itemId: string | undefined
|
||||
): [number, React.Dispatch<React.SetStateAction<number>>] { const [currentSeason, setCurrentSeason] = useState<number>(() => {
|
||||
const result = sessionStorage.getItem(`season-${itemId}`);
|
||||
return result ? Number(result) : 0;
|
||||
});
|
||||
|
||||
// Track if this is the initial load to avoid switching during episode updates
|
||||
const [hasInitialized, setHasInitialized] = useState(false); useEffect(() => {
|
||||
if (seasons.isSuccess && seasons.data?.Items) {
|
||||
const savedSeason = sessionStorage.getItem(`season-${itemId}`);
|
||||
|
||||
// Always re-evaluate the best season based on viewing progress
|
||||
let defaultSeasonIndex = 0;
|
||||
|
||||
// Map all seasons with their original index
|
||||
const allSeasonsWithIndex = seasons.data.Items.map((season: Season, index: number) => ({
|
||||
...season,
|
||||
originalIndex: index
|
||||
}));
|
||||
|
||||
// Separate regular seasons (not specials) and special seasons
|
||||
const regularSeasons = allSeasonsWithIndex.filter((season: Season) =>
|
||||
season.IndexNumber !== 0 && season.IndexNumber != null
|
||||
);
|
||||
const specialSeasons = allSeasonsWithIndex.filter((season: Season) =>
|
||||
season.IndexNumber === 0
|
||||
);
|
||||
|
||||
// Find the optimal season based on viewing progress
|
||||
if (regularSeasons.length > 0) {
|
||||
let targetSeason = regularSeasons[0];
|
||||
|
||||
// Look for the first season that isn't fully watched
|
||||
for (const season of regularSeasons) {
|
||||
// A season is considered "unwatched" if:
|
||||
// 1. The season itself isn't marked as played, AND
|
||||
// 2. The season has a play percentage less than 100%
|
||||
const isSeasonFullyWatched = season.UserData?.Played ||
|
||||
(season.UserData?.PlayedPercentage && season.UserData.PlayedPercentage >= 100);
|
||||
|
||||
if (!isSeasonFullyWatched) {
|
||||
targetSeason = season;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If the selected season is still fully watched, try to move to the next one
|
||||
const isTargetFullyWatched = targetSeason.UserData?.Played ||
|
||||
(targetSeason.UserData?.PlayedPercentage && targetSeason.UserData.PlayedPercentage >= 100);
|
||||
|
||||
if (isTargetFullyWatched) {
|
||||
const currentIndex = regularSeasons.findIndex((s: Season) => s.Id === targetSeason.Id);
|
||||
const nextSeasonIndex = currentIndex + 1;
|
||||
if (nextSeasonIndex < regularSeasons.length) {
|
||||
targetSeason = regularSeasons[nextSeasonIndex];
|
||||
}
|
||||
// If we're at the last season and it's fully watched, stay on it
|
||||
}
|
||||
|
||||
defaultSeasonIndex = targetSeason.originalIndex;
|
||||
}
|
||||
// Only fall back to special seasons if no regular seasons exist
|
||||
else if (specialSeasons.length > 0) {
|
||||
// For special seasons, just pick the first one
|
||||
defaultSeasonIndex = specialSeasons[0].originalIndex;
|
||||
}
|
||||
|
||||
// Smart season selection logic
|
||||
if (savedSeason) {
|
||||
const savedSeasonNumber = Number(savedSeason);
|
||||
const currentSeasonData = allSeasonsWithIndex[savedSeasonNumber];
|
||||
|
||||
// Check if user is currently in a special season
|
||||
const isInSpecialSeason = currentSeasonData?.IndexNumber === 0;
|
||||
|
||||
// Check if current season is fully complete
|
||||
const isCurrentSeasonComplete = currentSeasonData?.UserData?.Played ||
|
||||
(currentSeasonData?.UserData?.PlayedPercentage && currentSeasonData.UserData.PlayedPercentage >= 100);
|
||||
|
||||
if (isInSpecialSeason) {
|
||||
// For special seasons: advance to regular seasons if specials are complete
|
||||
if (isCurrentSeasonComplete && regularSeasons.length > 0) {
|
||||
// Special season is done, move to optimal regular season
|
||||
setCurrentSeason(defaultSeasonIndex);
|
||||
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
|
||||
} else if (!hasInitialized && regularSeasons.length > 0) {
|
||||
// Initial load: prioritize regular seasons over specials
|
||||
setCurrentSeason(defaultSeasonIndex);
|
||||
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
|
||||
} else {
|
||||
// Stay in specials (either no regular seasons or specials not complete)
|
||||
setCurrentSeason(savedSeasonNumber);
|
||||
}
|
||||
} else {
|
||||
// For regular seasons: advance to next season if current is complete
|
||||
if (isCurrentSeasonComplete) {
|
||||
// Find next season after current
|
||||
const currentRegularIndex = regularSeasons.findIndex((s: Season & { originalIndex: number }) => s.originalIndex === savedSeasonNumber);
|
||||
if (currentRegularIndex >= 0 && currentRegularIndex < regularSeasons.length - 1) {
|
||||
// Move to next regular season
|
||||
const nextSeason = regularSeasons[currentRegularIndex + 1];
|
||||
setCurrentSeason(nextSeason.originalIndex);
|
||||
sessionStorage.setItem(`season-${itemId}`, nextSeason.originalIndex.toString());
|
||||
} else {
|
||||
// At last season or use calculated optimal
|
||||
setCurrentSeason(defaultSeasonIndex);
|
||||
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
|
||||
}
|
||||
} else if (!hasInitialized && savedSeasonNumber !== defaultSeasonIndex) {
|
||||
// Initial load: use calculated optimal season
|
||||
setCurrentSeason(defaultSeasonIndex);
|
||||
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
|
||||
} else {
|
||||
// Stay in current season
|
||||
setCurrentSeason(savedSeasonNumber);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No saved season, use the calculated default
|
||||
setCurrentSeason(defaultSeasonIndex);
|
||||
sessionStorage.setItem(`season-${itemId}`, defaultSeasonIndex.toString());
|
||||
}
|
||||
|
||||
// Mark as initialized after first run
|
||||
if (!hasInitialized) {
|
||||
setHasInitialized(true);
|
||||
}
|
||||
}
|
||||
}, [seasons.isSuccess, seasons.data?.Items, itemId, hasInitialized]);
|
||||
return [currentSeason, setCurrentSeason];
|
||||
}
|
||||
|
||||
export default useDefaultSeason;
|
||||
Reference in new issue
Block a user