improve caption selection logic

This commit is contained in:
Pas 2025-12-22 11:51:15 -07:00
parent d88feda474
commit 94921e58dd
2 changed files with 32 additions and 7 deletions

View file

@ -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,

View file

@ -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]);
}