diff --git a/src/components/player/hooks/useCaptions.ts b/src/components/player/hooks/useCaptions.ts index aade9215..1df573f9 100644 --- a/src/components/player/hooks/useCaptions.ts +++ b/src/components/player/hooks/useCaptions.ts @@ -1,4 +1,4 @@ -import { useCallback, useMemo } from "react"; +import { useCallback, useEffect, useMemo } from "react"; import subsrt from "subsrt-ts"; import { downloadCaption, downloadWebVTT } from "@/backend/helpers/subs"; @@ -176,6 +176,30 @@ export function useCaptions() { await selectCaptionById(randomCaption.id); }, [lastSelectedLanguage, captions, selectedCaption, selectCaptionById]); + // Validate selected caption when caption list changes + useEffect(() => { + if (!selectedCaption) return; + + const isSelectedCaptionStillAvailable = captions.some( + (caption) => caption.id === selectedCaption.id, + ); + + if (!isSelectedCaptionStillAvailable) { + // Try to find a caption with the same language + const sameLanguageCaption = captions.find( + (caption) => caption.language === selectedCaption.language, + ); + + if (sameLanguageCaption) { + // Automatically select the first caption with the same language + selectCaptionById(sameLanguageCaption.id); + } else { + // No caption with the same language found, clear the selection + setCaption(null); + } + } + }, [captions, selectedCaption, setCaption, selectCaptionById]); + return { selectLanguage, disable, diff --git a/src/components/player/hooks/useInitializePlayer.ts b/src/components/player/hooks/useInitializePlayer.ts index f8fe96a7..f867c803 100644 --- a/src/components/player/hooks/useInitializePlayer.ts +++ b/src/components/player/hooks/useInitializePlayer.ts @@ -26,12 +26,13 @@ export function useInitializeSource() { ); const { selectLastUsedLanguageIfEnabled } = useCaptions(); - const funRef = useRef(selectLastUsedLanguageIfEnabled); - useEffect(() => { - funRef.current = selectLastUsedLanguageIfEnabled; - }, [selectLastUsedLanguageIfEnabled]); + // Only select subtitles on initial load, not when source changes + const hasInitializedRef = useRef(false); useEffect(() => { - if (sourceIdentifier) funRef.current(); - }, [sourceIdentifier]); + if (sourceIdentifier && !hasInitializedRef.current) { + hasInitializedRef.current = true; + selectLastUsedLanguageIfEnabled(); + } + }, [sourceIdentifier, selectLastUsedLanguageIfEnabled]); }