feat: KSPlayer as an option for iOS + other improvements (#1266)

This commit is contained in:
Fredrik Burmester
2026-01-03 13:05:50 +01:00
committed by GitHub
parent d1795c9df8
commit 74d86b5d12
191 changed files with 88479 additions and 2316 deletions

View File

@@ -0,0 +1,43 @@
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client";
import type { FC } from "react";
import { useCallback, useRef } from "react";
import { View, type ViewProps } from "react-native";
import { RoundButton } from "@/components/RoundButton";
import {
WatchlistSheet,
type WatchlistSheetRef,
} from "@/components/watchlists/WatchlistSheet";
import {
useItemInWatchlists,
useStreamystatsEnabled,
} from "@/hooks/useWatchlists";
interface Props extends ViewProps {
item: BaseItemDto;
}
export const AddToWatchlist: FC<Props> = ({ item, ...props }) => {
const streamystatsEnabled = useStreamystatsEnabled();
const sheetRef = useRef<WatchlistSheetRef>(null);
const { data: watchlistsContainingItem } = useItemInWatchlists(item.Id);
const isInAnyWatchlist = (watchlistsContainingItem?.length ?? 0) > 0;
const handlePress = useCallback(() => {
sheetRef.current?.open(item);
}, [item]);
// Don't render if Streamystats is not enabled
if (!streamystatsEnabled) return null;
return (
<View {...props}>
<RoundButton
size='large'
icon={isInAnyWatchlist ? "list" : "list-outline"}
onPress={handlePress}
/>
<WatchlistSheet ref={sheetRef} />
</View>
);
};

View File

@@ -109,7 +109,7 @@ export const DownloadItems: React.FC<DownloadProps> = ({
useEffect(() => {
setSelectedOptions(() => ({
bitrate: defaultBitrate,
mediaSource: defaultMediaSource,
mediaSource: defaultMediaSource ?? undefined,
subtitleIndex: defaultSubtitleIndex ?? -1,
audioIndex: defaultAudioIndex,
}));

View File

@@ -3,7 +3,7 @@ import {
type BottomSheetBackdropProps,
BottomSheetModal,
} from "@gorhom/bottom-sheet";
import { useCallback } from "react";
import { useCallback, useEffect } from "react";
import { useGlobalModal } from "@/providers/GlobalModalProvider";
/**
@@ -16,7 +16,13 @@ import { useGlobalModal } from "@/providers/GlobalModalProvider";
* after BottomSheetModalProvider.
*/
export const GlobalModal = () => {
const { hideModal, modalState, modalRef } = useGlobalModal();
const { hideModal, modalState, modalRef, isVisible } = useGlobalModal();
useEffect(() => {
if (isVisible && modalState.content) {
modalRef.current?.present();
}
}, [isVisible, modalState.content, modalRef]);
const handleSheetChanges = useCallback(
(index: number) => {

View File

@@ -11,6 +11,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { type Bitrate } from "@/components/BitrateSelector";
import { ItemImage } from "@/components/common/ItemImage";
import { DownloadSingleItem } from "@/components/DownloadItem";
import { ItemPeopleSections } from "@/components/item/ItemPeopleSections";
import { MediaSourceButton } from "@/components/MediaSourceButton";
import { OverviewText } from "@/components/OverviewText";
import { ParallaxScrollView } from "@/components/ParallaxPage";
@@ -18,7 +19,6 @@ import { ParallaxScrollView } from "@/components/ParallaxPage";
import { PlayButton } from "@/components/PlayButton";
import { PlayedStatus } from "@/components/PlayedStatus";
import { SimilarItems } from "@/components/SimilarItems";
import { CastAndCrew } from "@/components/series/CastAndCrew";
import { CurrentSeries } from "@/components/series/CurrentSeries";
import { SeasonEpisodesCarousel } from "@/components/series/SeasonEpisodesCarousel";
import useDefaultPlaySettings from "@/hooks/useDefaultPlaySettings";
@@ -29,9 +29,9 @@ import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
import { useSettings } from "@/utils/atoms/settings";
import { getLogoImageUrlById } from "@/utils/jellyfin/image/getLogoImageUrlById";
import { AddToFavorites } from "./AddToFavorites";
import { AddToWatchlist } from "./AddToWatchlist";
import { ItemHeader } from "./ItemHeader";
import { ItemTechnicalDetails } from "./ItemTechnicalDetails";
import { MoreMoviesWithActor } from "./MoreMoviesWithActor";
import { PlayInRemoteSessionButton } from "./PlayInRemoteSession";
const Chromecast = !Platform.isTV ? require("./Chromecast") : null;
@@ -67,18 +67,23 @@ export const ItemContent: React.FC<ItemContentProps> = React.memo(
SelectedOptions | undefined
>(undefined);
// Use itemWithSources for play settings since it has MediaSources data
const {
defaultAudioIndex,
defaultBitrate,
defaultMediaSource,
defaultSubtitleIndex,
} = useDefaultPlaySettings(item!, settings);
} = useDefaultPlaySettings(itemWithSources ?? item, settings);
const logoUrl = useMemo(
() => (item ? getLogoImageUrlById({ api, item }) : null),
[api, item],
);
const onLogoLoad = React.useCallback(() => {
setLoadingLogo(false);
}, []);
const loading = useMemo(() => {
return Boolean(logoUrl && loadingLogo);
}, [loadingLogo, logoUrl]);
@@ -87,7 +92,7 @@ export const ItemContent: React.FC<ItemContentProps> = React.memo(
useEffect(() => {
setSelectedOptions(() => ({
bitrate: defaultBitrate,
mediaSource: defaultMediaSource,
mediaSource: defaultMediaSource ?? undefined,
subtitleIndex: defaultSubtitleIndex ?? -1,
audioIndex: defaultAudioIndex,
}));
@@ -117,6 +122,7 @@ export const ItemContent: React.FC<ItemContentProps> = React.memo(
<PlayedStatus items={[item]} size='large' />
<AddToFavorites item={item} />
<AddToWatchlist item={item} />
</View>
)}
</View>
@@ -134,6 +140,7 @@ export const ItemContent: React.FC<ItemContentProps> = React.memo(
<PlayedStatus items={[item]} size='large' />
<AddToFavorites item={item} />
<AddToWatchlist item={item} />
</View>
)}
</View>
@@ -162,7 +169,7 @@ export const ItemContent: React.FC<ItemContentProps> = React.memo(
}}
>
<ParallaxScrollView
className={`flex-1 ${loading ? "opacity-0" : "opacity-100"}`}
className='flex-1'
headerHeight={headerHeight}
headerImage={
<View style={[{ flex: 1 }]}>
@@ -189,8 +196,8 @@ export const ItemContent: React.FC<ItemContentProps> = React.memo(
width: "100%",
}}
contentFit='contain'
onLoad={() => setLoadingLogo(false)}
onError={() => setLoadingLogo(false)}
onLoad={onLogoLoad}
onError={onLogoLoad}
/>
) : (
<View />
@@ -238,25 +245,10 @@ export const ItemContent: React.FC<ItemContentProps> = React.memo(
{item.Type !== "Program" && (
<>
{item.Type === "Episode" && !isOffline && (
<CurrentSeries item={item} className='mb-4' />
<CurrentSeries item={item} className='mb-2' />
)}
{!isOffline && (
<CastAndCrew item={item} className='mb-4' loading={loading} />
)}
{item.People && item.People.length > 0 && !isOffline && (
<View className='mb-4'>
{item.People.slice(0, 3).map((person, idx) => (
<MoreMoviesWithActor
currentItem={item}
key={idx}
actorId={person.Id!}
className='mb-4'
/>
))}
</View>
)}
<ItemPeopleSections item={item} isOffline={isOffline} />
{!isOffline && <SimilarItems itemId={item.Id} />}
</>

View File

@@ -3,6 +3,7 @@ import { getItemsApi } from "@jellyfin/sdk/lib/utils/api";
import { useQuery } from "@tanstack/react-query";
import { useAtom } from "jotai";
import type React from "react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { View, type ViewProps } from "react-native";
import { HorizontalScroll } from "@/components/common/HorizontalScroll";
@@ -10,16 +11,18 @@ import { Text } from "@/components/common/Text";
import { TouchableItemRouter } from "@/components/common/TouchableItemRouter";
import { ItemCardText } from "@/components/ItemCardText";
import MoviePoster from "@/components/posters/MoviePoster";
import { POSTER_CAROUSEL_HEIGHT } from "@/constants/Values";
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
import { getUserItemData } from "@/utils/jellyfin/user-library/getUserItemData";
interface Props extends ViewProps {
actorId: string;
actorName?: string | null;
currentItem: BaseItemDto;
}
export const MoreMoviesWithActor: React.FC<Props> = ({
actorId,
actorName,
currentItem,
...props
}) => {
@@ -27,19 +30,6 @@ export const MoreMoviesWithActor: React.FC<Props> = ({
const [user] = useAtom(userAtom);
const { t } = useTranslation();
const { data: actor } = useQuery({
queryKey: ["actor", actorId],
queryFn: async () => {
if (!api || !user?.Id) return null;
return await getUserItemData({
api,
userId: user.Id,
itemId: actorId,
});
},
enabled: !!api && !!user?.Id && !!actorId,
});
const { data: items, isLoading } = useQuery({
queryKey: ["actor", "movies", actorId, currentItem.Id],
queryFn: async () => {
@@ -72,29 +62,34 @@ export const MoreMoviesWithActor: React.FC<Props> = ({
enabled: !!api && !!user?.Id && !!actorId,
});
const renderItem = useCallback(
(item: BaseItemDto, idx: number) => (
<TouchableItemRouter
key={item.Id ?? idx}
item={item}
className='flex flex-col w-28'
>
<View>
<MoviePoster item={item} />
<ItemCardText item={item} />
</View>
</TouchableItemRouter>
),
[],
);
if (items?.length === 0) return null;
return (
<View {...props}>
<Text className='text-lg font-bold mb-2 px-4'>
{t("item_card.more_with", { name: actor?.Name })}
{t("item_card.more_with", { name: actorName ?? "" })}
</Text>
<HorizontalScroll
data={items}
loading={isLoading}
height={247}
renderItem={(item: BaseItemDto, idx: number) => (
<TouchableItemRouter
key={idx}
item={item}
className='flex flex-col w-28'
>
<View>
<MoviePoster item={item} />
<ItemCardText item={item} />
</View>
</TouchableItemRouter>
)}
height={POSTER_CAROUSEL_HEIGHT}
renderItem={renderItem}
/>
</View>
);

View File

@@ -54,9 +54,7 @@ const ToggleSwitch: React.FC<{ value: boolean }> = ({ value }) => (
className={`w-12 h-7 rounded-full ${value ? "bg-purple-600" : "bg-neutral-600"} flex-row items-center`}
>
<View
className={`w-5 h-5 rounded-full bg-white shadow-md transform transition-transform ${
value ? "translate-x-6" : "translate-x-1"
}`}
className={`w-5 h-5 rounded-full bg-white shadow-md transform transition-transform ${value ? "translate-x-6" : "translate-x-1"}`}
/>
</View>
);
@@ -73,9 +71,7 @@ const OptionItem: React.FC<{ option: Option; isLast?: boolean }> = ({
<TouchableOpacity
onPress={handlePress}
disabled={option.disabled}
className={`px-4 py-3 flex flex-row items-center justify-between ${
option.disabled ? "opacity-50" : ""
}`}
className={`px-4 py-3 flex flex-row items-center justify-between ${option.disabled ? "opacity-50" : ""}`}
>
<Text className='flex-1 text-white'>{option.label}</Text>
{isToggle ? (
@@ -219,11 +215,7 @@ const PlatformDropdownComponent = ({
return (
<Host style={expoUIConfig?.hostStyle}>
<ContextMenu>
<ContextMenu.Trigger>
<View className=''>
{trigger || <Button variant='bordered'>Show Menu</Button>}
</View>
</ContextMenu.Trigger>
<ContextMenu.Trigger>{trigger}</ContextMenu.Trigger>
<ContextMenu.Items>
{groups.flatMap((group, groupIndex) => {
// Check if this group has radio options

View File

@@ -1,5 +1,5 @@
import { useActionSheet } from "@expo/react-native-action-sheet";
import { Feather, Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { Feather, Ionicons } from "@expo/vector-icons";
import { BottomSheetView } from "@gorhom/bottom-sheet";
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client";
import { useRouter } from "expo-router";
@@ -280,7 +280,6 @@ export const PlayButton: React.FC<Props> = ({
]);
const onPress = useCallback(async () => {
console.log("onPress");
if (!item) return;
lightHapticFeedback();
@@ -474,52 +473,6 @@ export const PlayButton: React.FC<Props> = ({
),
}));
// if (Platform.OS === "ios")
// return (
// <Host
// style={{
// height: 50,
// flex: 1,
// flexShrink: 0,
// }}
// >
// <Button
// variant='glassProminent'
// onPress={onPress}
// color={effectiveColors.primary}
// modifiers={[fixedSize()]}
// >
// <View className='flex flex-row items-center space-x-2 h-full w-full justify-center -mb-3.5 '>
// <Animated.Text style={[animatedTextStyle, { fontWeight: "bold" }]}>
// {runtimeTicksToMinutes(
// (item?.RunTimeTicks || 0) -
// (item?.UserData?.PlaybackPositionTicks || 0),
// )}
// {(item?.UserData?.PlaybackPositionTicks || 0) > 0 && " left"}
// </Animated.Text>
// <Animated.Text style={animatedTextStyle}>
// <Ionicons name='play-circle' size={24} />
// </Animated.Text>
// {client && (
// <Animated.Text style={animatedTextStyle}>
// <Feather name='cast' size={22} />
// <CastButton tintColor='transparent' />
// </Animated.Text>
// )}
// {!client && settings?.openInVLC && (
// <Animated.Text style={animatedTextStyle}>
// <MaterialCommunityIcons
// name='vlc'
// size={18}
// color={animatedTextStyle.color}
// />
// </Animated.Text>
// )}
// </View>
// </Button>
// </Host>
// );
return (
<TouchableOpacity
disabled={!item}
@@ -569,15 +522,6 @@ export const PlayButton: React.FC<Props> = ({
<CastButton tintColor='transparent' />
</Animated.Text>
)}
{!client && settings?.openInVLC && (
<Animated.Text style={animatedTextStyle}>
<MaterialCommunityIcons
name='vlc'
size={18}
color={animatedTextStyle.color}
/>
</Animated.Text>
)}
</View>
</View>
</TouchableOpacity>

View File

@@ -1,4 +1,4 @@
import { Ionicons, MaterialCommunityIcons } from "@expo/vector-icons";
import { Ionicons } from "@expo/vector-icons";
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client";
import { useRouter } from "expo-router";
import { useAtom } from "jotai";
@@ -17,7 +17,6 @@ import Animated, {
import { useHaptic } from "@/hooks/useHaptic";
import type { ThemeColors } from "@/hooks/useImageColorsReturn";
import { itemThemeColorAtom } from "@/utils/atoms/primaryColor";
import { useSettings } from "@/utils/atoms/settings";
import { runtimeTicksToMinutes } from "@/utils/time";
import type { Button } from "./Button";
import type { SelectedOptions } from "./ItemContent";
@@ -50,7 +49,6 @@ export const PlayButton: React.FC<Props> = ({
const startColor = useSharedValue(effectiveColors);
const widthProgress = useSharedValue(0);
const colorChangeProgress = useSharedValue(0);
const { settings } = useSettings();
const lightHapticFeedback = useHaptic("light");
const goToPlayer = useCallback(
@@ -61,7 +59,6 @@ export const PlayButton: React.FC<Props> = ({
);
const onPress = () => {
console.log("onpress");
if (!item) return;
lightHapticFeedback();
@@ -207,15 +204,6 @@ export const PlayButton: React.FC<Props> = ({
<Animated.Text style={animatedTextStyle}>
<Ionicons name='play-circle' size={24} />
</Animated.Text>
{settings?.openInVLC && (
<Animated.Text style={animatedTextStyle}>
<MaterialCommunityIcons
name='vlc'
size={18}
color={animatedTextStyle.color}
/>
</Animated.Text>
)}
</View>
</View>
</TouchableOpacity>

View File

@@ -1,5 +1,6 @@
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
import type React from "react";
import { useCallback } from "react";
import { View, type ViewProps } from "react-native";
import { useMarkAsPlayed } from "@/hooks/useMarkAsPlayed";
import { RoundButton } from "./RoundButton";
@@ -14,14 +15,16 @@ export const PlayedStatus: React.FC<Props> = ({ items, ...props }) => {
const allPlayed = items.every((item) => item.UserData?.Played);
const toggle = useMarkAsPlayed(items);
const handlePress = useCallback(() => {
void toggle(!allPlayed);
}, [allPlayed, toggle]);
return (
<View {...props}>
<RoundButton
color={allPlayed ? "purple" : "white"}
icon={allPlayed ? "checkmark" : "checkmark"}
onPress={async () => {
await toggle(!allPlayed);
}}
onPress={handlePress}
size={props.size}
/>
</View>

View File

@@ -6,6 +6,7 @@ import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { View, type ViewProps } from "react-native";
import MoviePoster from "@/components/posters/MoviePoster";
import { POSTER_CAROUSEL_HEIGHT } from "@/constants/Values";
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
import { HorizontalScroll } from "./common/HorizontalScroll";
import { Text } from "./common/Text";
@@ -53,7 +54,7 @@ export const SimilarItems: React.FC<SimilarItemsProps> = ({
<HorizontalScroll
data={movies}
loading={isLoading}
height={247}
height={POSTER_CAROUSEL_HEIGHT}
noItemsText={t("item_card.no_similar_items_found")}
renderItem={(item: BaseItemDto, idx: number) => (
<TouchableItemRouter

View File

@@ -282,7 +282,7 @@ export const AppleTVCarousel: React.FC<AppleTVCarouselProps> = ({
if (currentItem) {
setSelectedOptions({
bitrate: defaultBitrate,
mediaSource: defaultMediaSource,
mediaSource: defaultMediaSource ?? undefined,
subtitleIndex: defaultSubtitleIndex ?? -1,
audioIndex: defaultAudioIndex,
});

View File

@@ -58,7 +58,7 @@ export const HorizontalScroll = <T,>(
if (!data || loading) {
return (
<View className='px-4 mb-2'>
<View className='px-4'>
<View className='bg-neutral-950 h-24 w-full rounded-md mb-2' />
<View className='bg-neutral-950 h-10 w-full rounded-md mb-1' />
</View>

View File

@@ -0,0 +1,42 @@
import { TouchableOpacity, View } from "react-native";
import { Colors } from "@/constants/Colors";
import { Text } from "./Text";
type Props = {
title: string;
actionLabel?: string;
actionDisabled?: boolean;
onPressAction?: () => void;
};
export const SectionHeader: React.FC<Props> = ({
title,
actionLabel,
actionDisabled = false,
onPressAction,
}) => {
const shouldShowAction = Boolean(actionLabel) && Boolean(onPressAction);
return (
<View className='px-4 flex flex-row items-center justify-between mb-2'>
<Text className='text-lg font-bold text-neutral-100'>{title}</Text>
{shouldShowAction && (
<TouchableOpacity
onPress={onPressAction}
disabled={actionDisabled}
accessibilityRole='button'
accessibilityLabel={actionLabel}
className='py-1 pl-3'
>
<Text
style={{
color: actionDisabled ? "rgba(255,255,255,0.4)" : Colors.primary,
}}
>
{actionLabel}
</Text>
</TouchableOpacity>
)}
</View>
);
};

View File

@@ -16,6 +16,10 @@ export const itemRouter = (item: BaseItemDto, from: string) => {
return `/(auth)/(tabs)/${from}/livetv`;
}
if ("CollectionType" in item && item.CollectionType === "music") {
return `/(auth)/(tabs)/(libraries)/music/${item.Id}`;
}
if (item.Type === "Series") {
return `/(auth)/(tabs)/${from}/series/${item.Id}`;
}
@@ -50,6 +54,13 @@ export const getItemNavigation = (item: BaseItemDto, _from: string) => {
};
}
if ("CollectionType" in item && item.CollectionType === "music") {
return {
pathname: "/music/[libraryId]" as const,
params: { libraryId: item.Id! },
};
}
if (item.Type === "Series") {
return {
pathname: "/series/[id]" as const,
@@ -99,6 +110,25 @@ export const TouchableItemRouter: React.FC<PropsWithChildren<Props>> = ({
const from = (segments as string[])[2] || "(home)";
const handlePress = useCallback(() => {
// For offline mode, we still need to use query params
if (isOffline) {
const url = `${itemRouter(item, from)}&offline=true`;
router.push(url as any);
return;
}
// Force music libraries to navigate via the explicit string route.
// This avoids losing the dynamic [libraryId] param when going through a nested navigator.
if ("CollectionType" in item && item.CollectionType === "music") {
router.push(itemRouter(item, from) as any);
return;
}
const navigation = getItemNavigation(item, from);
router.push(navigation as any);
}, [from, isOffline, item, router]);
const showActionSheet = useCallback(() => {
if (
!(
@@ -108,13 +138,14 @@ export const TouchableItemRouter: React.FC<PropsWithChildren<Props>> = ({
)
)
return;
const options = [
const options: string[] = [
"Mark as Played",
"Mark as Not Played",
isFavorite ? "Unmark as Favorite" : "Mark as Favorite",
"Cancel",
];
const cancelButtonIndex = 3;
const cancelButtonIndex = options.length - 1;
showActionSheetWithOptions(
{
@@ -131,28 +162,24 @@ export const TouchableItemRouter: React.FC<PropsWithChildren<Props>> = ({
}
},
);
}, [showActionSheetWithOptions, isFavorite, markAsPlayedStatus]);
}, [
showActionSheetWithOptions,
isFavorite,
markAsPlayedStatus,
toggleFavorite,
]);
if (
from === "(home)" ||
from === "(search)" ||
from === "(libraries)" ||
from === "(favorites)"
from === "(favorites)" ||
from === "(watchlists)"
)
return (
<TouchableOpacity
onLongPress={showActionSheet}
onPress={() => {
if (isOffline) {
// For offline mode, we still need to use query params
const url = `${itemRouter(item, from)}&offline=true`;
router.push(url as any);
return;
}
const navigation = getItemNavigation(item, from);
router.push(navigation as any);
}}
onPress={handlePress}
{...props}
>
{children}

View File

@@ -2,6 +2,7 @@ import { Ionicons } from "@expo/vector-icons";
import { useAtom } from "jotai";
import { TouchableOpacity, type TouchableOpacityProps } from "react-native";
import {
filterByAtom,
genreFilterAtom,
tagsFilterAtom,
yearFilterAtom,
@@ -13,11 +14,13 @@ export const ResetFiltersButton: React.FC<Props> = ({ ...props }) => {
const [selectedGenres, setSelectedGenres] = useAtom(genreFilterAtom);
const [selectedTags, setSelectedTags] = useAtom(tagsFilterAtom);
const [selectedYears, setSelectedYears] = useAtom(yearFilterAtom);
const [selectedFilters, setSelectedFilters] = useAtom(filterByAtom);
if (
selectedGenres.length === 0 &&
selectedTags.length === 0 &&
selectedYears.length === 0
selectedYears.length === 0 &&
selectedFilters.length === 0
) {
return null;
}
@@ -28,6 +31,7 @@ export const ResetFiltersButton: React.FC<Props> = ({ ...props }) => {
setSelectedGenres([]);
setSelectedTags([]);
setSelectedYears([]);
setSelectedFilters([]);
}}
className='bg-purple-600 rounded-full w-[30px] h-[30px] flex items-center justify-center mr-1'
{...props}

View File

@@ -2,6 +2,7 @@ import type { Api } from "@jellyfin/sdk";
import type { BaseItemKind } from "@jellyfin/sdk/lib/generated-client";
import { getItemsApi } from "@jellyfin/sdk/lib/utils/api";
import { Image } from "expo-image";
import { useRouter } from "expo-router";
import { t } from "i18next";
import { useAtom } from "jotai";
import { useCallback, useEffect, useState } from "react";
@@ -22,8 +23,10 @@ type FavoriteTypes =
type EmptyState = Record<FavoriteTypes, boolean>;
export const Favorites = () => {
const router = useRouter();
const [api] = useAtom(apiAtom);
const [user] = useAtom(userAtom);
const pageSize = 20;
const [emptyState, setEmptyState] = useState<EmptyState>({
Series: false,
Movie: false,
@@ -91,35 +94,77 @@ export const Favorites = () => {
const fetchFavoriteSeries = useCallback(
({ pageParam }: { pageParam: number }) =>
fetchFavoritesByType("Series", pageParam),
[fetchFavoritesByType],
fetchFavoritesByType("Series", pageParam, pageSize),
[fetchFavoritesByType, pageSize],
);
const fetchFavoriteMovies = useCallback(
({ pageParam }: { pageParam: number }) =>
fetchFavoritesByType("Movie", pageParam),
[fetchFavoritesByType],
fetchFavoritesByType("Movie", pageParam, pageSize),
[fetchFavoritesByType, pageSize],
);
const fetchFavoriteEpisodes = useCallback(
({ pageParam }: { pageParam: number }) =>
fetchFavoritesByType("Episode", pageParam),
[fetchFavoritesByType],
fetchFavoritesByType("Episode", pageParam, pageSize),
[fetchFavoritesByType, pageSize],
);
const fetchFavoriteVideos = useCallback(
({ pageParam }: { pageParam: number }) =>
fetchFavoritesByType("Video", pageParam),
[fetchFavoritesByType],
fetchFavoritesByType("Video", pageParam, pageSize),
[fetchFavoritesByType, pageSize],
);
const fetchFavoriteBoxsets = useCallback(
({ pageParam }: { pageParam: number }) =>
fetchFavoritesByType("BoxSet", pageParam),
[fetchFavoritesByType],
fetchFavoritesByType("BoxSet", pageParam, pageSize),
[fetchFavoritesByType, pageSize],
);
const fetchFavoritePlaylists = useCallback(
({ pageParam }: { pageParam: number }) =>
fetchFavoritesByType("Playlist", pageParam),
[fetchFavoritesByType],
fetchFavoritesByType("Playlist", pageParam, pageSize),
[fetchFavoritesByType, pageSize],
);
const handleSeeAllSeries = useCallback(() => {
router.push({
pathname: "/(auth)/(tabs)/(favorites)/see-all",
params: { type: "Series", title: t("favorites.series") },
} as any);
}, [router]);
const handleSeeAllMovies = useCallback(() => {
router.push({
pathname: "/(auth)/(tabs)/(favorites)/see-all",
params: { type: "Movie", title: t("favorites.movies") },
} as any);
}, [router]);
const handleSeeAllEpisodes = useCallback(() => {
router.push({
pathname: "/(auth)/(tabs)/(favorites)/see-all",
params: { type: "Episode", title: t("favorites.episodes") },
} as any);
}, [router]);
const handleSeeAllVideos = useCallback(() => {
router.push({
pathname: "/(auth)/(tabs)/(favorites)/see-all",
params: { type: "Video", title: t("favorites.videos") },
} as any);
}, [router]);
const handleSeeAllBoxsets = useCallback(() => {
router.push({
pathname: "/(auth)/(tabs)/(favorites)/see-all",
params: { type: "BoxSet", title: t("favorites.boxsets") },
} as any);
}, [router]);
const handleSeeAllPlaylists = useCallback(() => {
router.push({
pathname: "/(auth)/(tabs)/(favorites)/see-all",
params: { type: "Playlist", title: t("favorites.playlists") },
} as any);
}, [router]);
return (
<View className='flex flex-co gap-y-4'>
{areAllEmpty() && (
@@ -143,6 +188,8 @@ export const Favorites = () => {
queryKey={["home", "favorites", "series"]}
title={t("favorites.series")}
hideIfEmpty
pageSize={pageSize}
onPressSeeAll={handleSeeAllSeries}
/>
<InfiniteScrollingCollectionList
queryFn={fetchFavoriteMovies}
@@ -150,30 +197,40 @@ export const Favorites = () => {
title={t("favorites.movies")}
hideIfEmpty
orientation='vertical'
pageSize={pageSize}
onPressSeeAll={handleSeeAllMovies}
/>
<InfiniteScrollingCollectionList
queryFn={fetchFavoriteEpisodes}
queryKey={["home", "favorites", "episodes"]}
title={t("favorites.episodes")}
hideIfEmpty
pageSize={pageSize}
onPressSeeAll={handleSeeAllEpisodes}
/>
<InfiniteScrollingCollectionList
queryFn={fetchFavoriteVideos}
queryKey={["home", "favorites", "videos"]}
title={t("favorites.videos")}
hideIfEmpty
pageSize={pageSize}
onPressSeeAll={handleSeeAllVideos}
/>
<InfiniteScrollingCollectionList
queryFn={fetchFavoriteBoxsets}
queryKey={["home", "favorites", "boxsets"]}
title={t("favorites.boxsets")}
hideIfEmpty
pageSize={pageSize}
onPressSeeAll={handleSeeAllBoxsets}
/>
<InfiniteScrollingCollectionList
queryFn={fetchFavoritePlaylists}
queryKey={["home", "favorites", "playlists"]}
title={t("favorites.playlists")}
hideIfEmpty
pageSize={pageSize}
onPressSeeAll={handleSeeAllPlaylists}
/>
</View>
);

View File

@@ -28,6 +28,8 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Button } from "@/components/Button";
import { Text } from "@/components/common/Text";
import { InfiniteScrollingCollectionList } from "@/components/home/InfiniteScrollingCollectionList";
import { StreamystatsPromotedWatchlists } from "@/components/home/StreamystatsPromotedWatchlists";
import { StreamystatsRecommendations } from "@/components/home/StreamystatsRecommendations";
import { Loader } from "@/components/Loader";
import { MediaListSection } from "@/components/medialists/MediaListSection";
import { Colors } from "@/constants/Colors";
@@ -45,12 +47,14 @@ type InfiniteScrollingCollectionListSection = {
queryFn: QueryFunction<BaseItemDto[], any, number>;
orientation?: "horizontal" | "vertical";
pageSize?: number;
priority?: 1 | 2; // 1 = high priority (loads first), 2 = low priority
};
type MediaListSectionType = {
type: "MediaListSection";
queryKey: (string | undefined)[];
queryFn: QueryFunction<BaseItemDto>;
priority?: 1 | 2;
};
type Section = InfiniteScrollingCollectionListSection | MediaListSectionType;
@@ -74,7 +78,7 @@ export const Home = () => {
retryCheck,
} = useNetworkStatus();
const invalidateCache = useInvalidatePlaybackProgressCache();
const [scrollY, setScrollY] = useState(0);
const [loadedSections, setLoadedSections] = useState<Set<string>>(new Set());
useEffect(() => {
if (isConnected && !prevIsConnected.current) {
@@ -172,6 +176,7 @@ export const Home = () => {
const refetch = async () => {
setLoading(true);
setLoadedSections(new Set());
await refreshStreamyfinPluginSettings();
await invalidateCache();
setLoading(false);
@@ -194,10 +199,10 @@ export const Home = () => {
(
await getUserLibraryApi(api).getLatestMedia({
userId: user?.Id,
limit: 100, // Fetch a larger set for pagination
fields: ["PrimaryImageAspectRatio", "Path", "Genres"],
limit: 10,
fields: ["PrimaryImageAspectRatio"],
imageTypeLimit: 1,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
enableImageTypes: ["Primary", "Backdrop", "Thumb"],
includeItemTypes,
parentId,
})
@@ -236,64 +241,143 @@ export const Home = () => {
);
});
// Helper to sort items by most recent activity
const sortByRecentActivity = (items: BaseItemDto[]): BaseItemDto[] => {
return items.sort((a, b) => {
const dateA = a.UserData?.LastPlayedDate || a.DateCreated || "";
const dateB = b.UserData?.LastPlayedDate || b.DateCreated || "";
return new Date(dateB).getTime() - new Date(dateA).getTime();
});
};
// Helper to deduplicate items by ID
const deduplicateById = (items: BaseItemDto[]): BaseItemDto[] => {
const seen = new Set<string>();
return items.filter((item) => {
if (!item.Id || seen.has(item.Id)) return false;
seen.add(item.Id);
return true;
});
};
// Build the first sections based on merge setting
const firstSections: Section[] = settings.mergeNextUpAndContinueWatching
? [
{
title: t("home.continue_and_next_up"),
queryKey: ["home", "continueAndNextUp"],
queryFn: async ({ pageParam = 0 }) => {
// Fetch both in parallel
const [resumeResponse, nextUpResponse] = await Promise.all([
getItemsApi(api).getResumeItems({
userId: user.Id,
enableImageTypes: ["Primary", "Backdrop", "Thumb"],
includeItemTypes: ["Movie", "Series", "Episode"],
startIndex: 0,
limit: 20,
}),
getTvShowsApi(api).getNextUp({
userId: user?.Id,
startIndex: 0,
limit: 20,
enableImageTypes: ["Primary", "Backdrop", "Thumb"],
enableResumable: false,
}),
]);
const resumeItems = resumeResponse.data.Items || [];
const nextUpItems = nextUpResponse.data.Items || [];
// Combine, sort by recent activity, deduplicate
const combined = [...resumeItems, ...nextUpItems];
const sorted = sortByRecentActivity(combined);
const deduplicated = deduplicateById(sorted);
// Paginate client-side
return deduplicated.slice(pageParam, pageParam + 10);
},
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
priority: 1,
},
]
: [
{
title: t("home.continue_watching"),
queryKey: ["home", "resumeItems"],
queryFn: async ({ pageParam = 0 }) =>
(
await getItemsApi(api).getResumeItems({
userId: user.Id,
enableImageTypes: ["Primary", "Backdrop", "Thumb"],
includeItemTypes: ["Movie", "Series", "Episode"],
startIndex: pageParam,
limit: 10,
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
priority: 1,
},
{
title: t("home.next_up"),
queryKey: ["home", "nextUp-all"],
queryFn: async ({ pageParam = 0 }) =>
(
await getTvShowsApi(api).getNextUp({
userId: user?.Id,
startIndex: pageParam,
limit: 10,
enableImageTypes: ["Primary", "Backdrop", "Thumb"],
enableResumable: false,
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
priority: 1,
},
];
const ss: Section[] = [
{
title: t("home.continue_watching"),
queryKey: ["home", "resumeItems"],
queryFn: async ({ pageParam = 0 }) =>
(
await getItemsApi(api).getResumeItems({
userId: user.Id,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
includeItemTypes: ["Movie", "Series", "Episode"],
fields: ["Genres"],
startIndex: pageParam,
limit: 10,
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
},
{
title: t("home.next_up"),
queryKey: ["home", "nextUp-all"],
queryFn: async ({ pageParam = 0 }) =>
(
await getTvShowsApi(api).getNextUp({
userId: user?.Id,
fields: ["MediaSourceCount", "Genres"],
startIndex: pageParam,
limit: 10,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
enableResumable: false,
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
},
...latestMediaViews,
{
title: t("home.suggested_movies"),
queryKey: ["home", "suggestedMovies", user?.Id],
queryFn: async ({ pageParam = 0 }) =>
(
await getSuggestionsApi(api).getSuggestions({
userId: user?.Id,
startIndex: pageParam,
limit: 10,
mediaType: ["Video"],
type: ["Movie"],
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "vertical",
pageSize: 10,
},
...firstSections,
...latestMediaViews.map((s) => ({ ...s, priority: 2 as const })),
// Only show Jellyfin suggested movies if StreamyStats recommendations are disabled
...(!settings?.streamyStatsMovieRecommendations
? [
{
title: t("home.suggested_movies"),
queryKey: ["home", "suggestedMovies", user?.Id],
queryFn: async ({ pageParam = 0 }: { pageParam?: number }) =>
(
await getSuggestionsApi(api).getSuggestions({
userId: user?.Id,
startIndex: pageParam,
limit: 10,
mediaType: ["Video"],
type: ["Movie"],
})
).data.Items || [],
type: "InfiniteScrollingCollectionList" as const,
orientation: "vertical" as const,
pageSize: 10,
priority: 2 as const,
},
]
: []),
];
return ss;
}, [api, user?.Id, collections, t, createCollectionConfig]);
}, [
api,
user?.Id,
collections,
t,
createCollectionConfig,
settings?.streamyStatsMovieRecommendations,
settings.mergeNextUpAndContinueWatching,
]);
const customSections = useMemo(() => {
if (!api || !user?.Id || !settings?.home?.sections) return [];
@@ -322,10 +406,9 @@ export const Home = () => {
if (section.nextUp) {
const response = await getTvShowsApi(api).getNextUp({
userId: user?.Id,
fields: ["MediaSourceCount", "Genres"],
startIndex: pageParam,
limit: section.nextUp?.limit || pageSize,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
enableImageTypes: ["Primary", "Backdrop", "Thumb"],
enableResumable: section.nextUp?.enableResumable,
enableRewatching: section.nextUp?.enableRewatching,
});
@@ -338,7 +421,7 @@ export const Home = () => {
await getUserLibraryApi(api).getLatestMedia({
userId: user?.Id,
includeItemTypes: section.latest?.includeItemTypes,
limit: section.latest?.limit || 100, // Fetch larger set
limit: section.latest?.limit || 10,
isPlayed: section.latest?.isPlayed,
groupItems: section.latest?.groupItems,
})
@@ -367,6 +450,8 @@ export const Home = () => {
type: "InfiniteScrollingCollectionList",
orientation: section?.orientation || "vertical",
pageSize,
// First 2 custom sections are high priority
priority: index < 2 ? 1 : 2,
});
});
return ss;
@@ -374,6 +459,25 @@ export const Home = () => {
const sections = settings?.home?.sections ? customSections : defaultSections;
// Get all high priority section keys and check if all have loaded
const highPrioritySectionKeys = useMemo(() => {
return sections
.filter((s) => s.priority === 1)
.map((s) => s.queryKey.join("-"));
}, [sections]);
const allHighPriorityLoaded = useMemo(() => {
return highPrioritySectionKeys.every((key) => loadedSections.has(key));
}, [highPrioritySectionKeys, loadedSections]);
const markSectionLoaded = useCallback(
(queryKey: (string | undefined | null)[]) => {
const key = queryKey.join("-");
setLoadedSections((prev) => new Set(prev).add(key));
},
[],
);
if (!isConnected || serverConnected !== true) {
let title = "";
let subtitle = "";
@@ -451,10 +555,6 @@ export const Home = () => {
ref={scrollRef}
nestedScrollEnabled
contentInsetAdjustmentBehavior='automatic'
onScroll={(event) => {
setScrollY(event.nativeEvent.contentOffset.y - 500);
}}
scrollEventThrottle={16}
refreshControl={
<RefreshControl
refreshing={loading}
@@ -474,28 +574,77 @@ export const Home = () => {
style={{ paddingTop: Platform.OS === "android" ? 10 : 0 }}
>
{sections.map((section, index) => {
// Render Streamystats sections after Continue Watching and Next Up
// When merged, they appear after index 0; otherwise after index 1
const streamystatsIndex = settings.mergeNextUpAndContinueWatching
? 0
: 1;
const hasStreamystatsContent =
settings.streamyStatsMovieRecommendations ||
settings.streamyStatsSeriesRecommendations ||
settings.streamyStatsPromotedWatchlists;
const streamystatsSections =
index === streamystatsIndex && hasStreamystatsContent ? (
<View
key='streamystats-sections'
className='flex flex-col space-y-4'
>
{settings.streamyStatsMovieRecommendations && (
<StreamystatsRecommendations
title={t(
"home.settings.plugins.streamystats.recommended_movies",
)}
type='Movie'
enabled={allHighPriorityLoaded}
/>
)}
{settings.streamyStatsSeriesRecommendations && (
<StreamystatsRecommendations
title={t(
"home.settings.plugins.streamystats.recommended_series",
)}
type='Series'
enabled={allHighPriorityLoaded}
/>
)}
{settings.streamyStatsPromotedWatchlists && (
<StreamystatsPromotedWatchlists
enabled={allHighPriorityLoaded}
/>
)}
</View>
) : null;
if (section.type === "InfiniteScrollingCollectionList") {
const isHighPriority = section.priority === 1;
return (
<InfiniteScrollingCollectionList
key={index}
title={section.title}
queryKey={section.queryKey}
queryFn={section.queryFn}
orientation={section.orientation}
hideIfEmpty
pageSize={section.pageSize}
/>
<View key={index} className='flex flex-col space-y-4'>
<InfiniteScrollingCollectionList
title={section.title}
queryKey={section.queryKey}
queryFn={section.queryFn}
orientation={section.orientation}
hideIfEmpty
pageSize={section.pageSize}
enabled={isHighPriority || allHighPriorityLoaded}
onLoaded={
isHighPriority
? () => markSectionLoaded(section.queryKey)
: undefined
}
/>
{streamystatsSections}
</View>
);
}
if (section.type === "MediaListSection") {
return (
<MediaListSection
key={index}
queryKey={section.queryKey}
queryFn={section.queryFn}
scrollY={scrollY}
enableLazyLoading={true}
/>
<View key={index} className='flex flex-col space-y-4'>
<MediaListSection
queryKey={section.queryKey}
queryFn={section.queryFn}
/>
{streamystatsSections}
</View>
);
}
return null;

View File

@@ -30,6 +30,8 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Button } from "@/components/Button";
import { Text } from "@/components/common/Text";
import { InfiniteScrollingCollectionList } from "@/components/home/InfiniteScrollingCollectionList";
import { StreamystatsPromotedWatchlists } from "@/components/home/StreamystatsPromotedWatchlists";
import { StreamystatsRecommendations } from "@/components/home/StreamystatsRecommendations";
import { Loader } from "@/components/Loader";
import { MediaListSection } from "@/components/medialists/MediaListSection";
import { Colors } from "@/constants/Colors";
@@ -241,64 +243,143 @@ export const HomeWithCarousel = () => {
);
});
// Helper to sort items by most recent activity
const sortByRecentActivity = (items: BaseItemDto[]): BaseItemDto[] => {
return items.sort((a, b) => {
const dateA = a.UserData?.LastPlayedDate || a.DateCreated || "";
const dateB = b.UserData?.LastPlayedDate || b.DateCreated || "";
return new Date(dateB).getTime() - new Date(dateA).getTime();
});
};
// Helper to deduplicate items by ID
const deduplicateById = (items: BaseItemDto[]): BaseItemDto[] => {
const seen = new Set<string>();
return items.filter((item) => {
if (!item.Id || seen.has(item.Id)) return false;
seen.add(item.Id);
return true;
});
};
// Build the first sections based on merge setting
const firstSections: Section[] = settings.mergeNextUpAndContinueWatching
? [
{
title: t("home.continue_and_next_up"),
queryKey: ["home", "continueAndNextUp"],
queryFn: async ({ pageParam = 0 }) => {
// Fetch both in parallel
const [resumeResponse, nextUpResponse] = await Promise.all([
getItemsApi(api).getResumeItems({
userId: user.Id,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
includeItemTypes: ["Movie", "Series", "Episode"],
fields: ["Genres"],
startIndex: 0,
limit: 20,
}),
getTvShowsApi(api).getNextUp({
userId: user?.Id,
fields: ["MediaSourceCount", "Genres"],
startIndex: 0,
limit: 20,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
enableResumable: false,
}),
]);
const resumeItems = resumeResponse.data.Items || [];
const nextUpItems = nextUpResponse.data.Items || [];
// Combine, sort by recent activity, deduplicate
const combined = [...resumeItems, ...nextUpItems];
const sorted = sortByRecentActivity(combined);
const deduplicated = deduplicateById(sorted);
// Paginate client-side
return deduplicated.slice(pageParam, pageParam + 10);
},
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
},
]
: [
{
title: t("home.continue_watching"),
queryKey: ["home", "resumeItems"],
queryFn: async ({ pageParam = 0 }) =>
(
await getItemsApi(api).getResumeItems({
userId: user.Id,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
includeItemTypes: ["Movie", "Series", "Episode"],
fields: ["Genres"],
startIndex: pageParam,
limit: 10,
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
},
{
title: t("home.next_up"),
queryKey: ["home", "nextUp-all"],
queryFn: async ({ pageParam = 0 }) =>
(
await getTvShowsApi(api).getNextUp({
userId: user?.Id,
fields: ["MediaSourceCount", "Genres"],
startIndex: pageParam,
limit: 10,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
enableResumable: false,
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
},
];
const ss: Section[] = [
{
title: t("home.continue_watching"),
queryKey: ["home", "resumeItems"],
queryFn: async ({ pageParam = 0 }) =>
(
await getItemsApi(api).getResumeItems({
userId: user.Id,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
includeItemTypes: ["Movie", "Series", "Episode"],
fields: ["Genres"],
startIndex: pageParam,
limit: 10,
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
},
{
title: t("home.next_up"),
queryKey: ["home", "nextUp-all"],
queryFn: async ({ pageParam = 0 }) =>
(
await getTvShowsApi(api).getNextUp({
userId: user?.Id,
fields: ["MediaSourceCount", "Genres"],
startIndex: pageParam,
limit: 10,
enableImageTypes: ["Primary", "Backdrop", "Thumb", "Logo"],
enableResumable: false,
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "horizontal",
pageSize: 10,
},
...firstSections,
...latestMediaViews,
{
title: t("home.suggested_movies"),
queryKey: ["home", "suggestedMovies", user?.Id],
queryFn: async ({ pageParam = 0 }) =>
(
await getSuggestionsApi(api).getSuggestions({
userId: user?.Id,
startIndex: pageParam,
limit: 10,
mediaType: ["Video"],
type: ["Movie"],
})
).data.Items || [],
type: "InfiniteScrollingCollectionList",
orientation: "vertical",
pageSize: 10,
},
// Only show Jellyfin suggested movies if StreamyStats recommendations are disabled
...(!settings?.streamyStatsMovieRecommendations
? [
{
title: t("home.suggested_movies"),
queryKey: ["home", "suggestedMovies", user?.Id],
queryFn: async ({ pageParam = 0 }: { pageParam?: number }) =>
(
await getSuggestionsApi(api).getSuggestions({
userId: user?.Id,
startIndex: pageParam,
limit: 10,
mediaType: ["Video"],
type: ["Movie"],
})
).data.Items || [],
type: "InfiniteScrollingCollectionList" as const,
orientation: "vertical" as const,
pageSize: 10,
},
]
: []),
];
return ss;
}, [api, user?.Id, collections, t, createCollectionConfig]);
}, [
api,
user?.Id,
collections,
t,
createCollectionConfig,
settings?.streamyStatsMovieRecommendations,
settings.mergeNextUpAndContinueWatching,
]);
const customSections = useMemo(() => {
if (!api || !user?.Id || !settings?.home?.sections) return [];
@@ -477,28 +558,66 @@ export const HomeWithCarousel = () => {
>
<View className='flex flex-col space-y-4'>
{sections.map((section, index) => {
// Render Streamystats sections after Continue Watching and Next Up
// When merged, they appear after index 0; otherwise after index 1
const streamystatsIndex = settings.mergeNextUpAndContinueWatching
? 0
: 1;
const hasStreamystatsContent =
settings.streamyStatsMovieRecommendations ||
settings.streamyStatsSeriesRecommendations ||
settings.streamyStatsPromotedWatchlists;
const streamystatsSections =
index === streamystatsIndex && hasStreamystatsContent ? (
<>
{settings.streamyStatsMovieRecommendations && (
<StreamystatsRecommendations
title={t(
"home.settings.plugins.streamystats.recommended_movies",
)}
type='Movie'
/>
)}
{settings.streamyStatsSeriesRecommendations && (
<StreamystatsRecommendations
title={t(
"home.settings.plugins.streamystats.recommended_series",
)}
type='Series'
/>
)}
{settings.streamyStatsPromotedWatchlists && (
<StreamystatsPromotedWatchlists />
)}
</>
) : null;
if (section.type === "InfiniteScrollingCollectionList") {
return (
<InfiniteScrollingCollectionList
key={index}
title={section.title}
queryKey={section.queryKey}
queryFn={section.queryFn}
orientation={section.orientation}
hideIfEmpty
pageSize={section.pageSize}
/>
<View key={index} className='flex flex-col space-y-4'>
<InfiniteScrollingCollectionList
title={section.title}
queryKey={section.queryKey}
queryFn={section.queryFn}
orientation={section.orientation}
hideIfEmpty
pageSize={section.pageSize}
/>
{streamystatsSections}
</View>
);
}
if (section.type === "MediaListSection") {
return (
<MediaListSection
key={index}
queryKey={section.queryKey}
queryFn={section.queryFn}
scrollY={scrollY}
enableLazyLoading={true}
/>
<View key={index} className='flex flex-col space-y-4'>
<MediaListSection
queryKey={section.queryKey}
queryFn={section.queryFn}
scrollY={scrollY}
enableLazyLoading={true}
/>
{streamystatsSections}
</View>
);
}
return null;

View File

@@ -4,7 +4,7 @@ import {
type QueryKey,
useInfiniteQuery,
} from "@tanstack/react-query";
import { useMemo } from "react";
import { useEffect, useMemo, useRef } from "react";
import { useTranslation } from "react-i18next";
import {
ActivityIndicator,
@@ -12,6 +12,7 @@ import {
View,
type ViewProps,
} from "react-native";
import { SectionHeader } from "@/components/common/SectionHeader";
import { Text } from "@/components/common/Text";
import MoviePoster from "@/components/posters/MoviePoster";
import { Colors } from "../../constants/Colors";
@@ -28,6 +29,9 @@ interface Props extends ViewProps {
queryFn: QueryFunction<BaseItemDto[], QueryKey, number>;
hideIfEmpty?: boolean;
pageSize?: number;
onPressSeeAll?: () => void;
enabled?: boolean;
onLoaded?: () => void;
}
export const InfiniteScrollingCollectionList: React.FC<Props> = ({
@@ -38,32 +42,67 @@ export const InfiniteScrollingCollectionList: React.FC<Props> = ({
queryKey,
hideIfEmpty = false,
pageSize = 10,
onPressSeeAll,
enabled = true,
onLoaded,
...props
}) => {
const { data, isLoading, isFetchingNextPage, hasNextPage, fetchNextPage } =
useInfiniteQuery({
queryKey: queryKey,
queryFn: ({ pageParam = 0, ...context }) =>
queryFn({ ...context, queryKey, pageParam }),
getNextPageParam: (lastPage, allPages) => {
// If the last page has fewer items than pageSize, we've reached the end
if (lastPage.length < pageSize) {
return undefined;
}
// Otherwise, return the next start index
return allPages.length * pageSize;
},
initialPageParam: 0,
staleTime: 60 * 1000, // 1 minute
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: true,
});
const effectivePageSize = Math.max(1, pageSize);
const hasCalledOnLoaded = useRef(false);
const {
data,
isLoading,
isFetchingNextPage,
hasNextPage,
fetchNextPage,
isSuccess,
} = useInfiniteQuery({
queryKey: queryKey,
queryFn: ({ pageParam = 0, ...context }) =>
queryFn({ ...context, queryKey, pageParam }),
getNextPageParam: (lastPage, allPages) => {
// If the last page has fewer items than pageSize, we've reached the end
if (lastPage.length < effectivePageSize) {
return undefined;
}
// Otherwise, return the next start index based on how many items we already loaded.
// This avoids overlaps if the server/page size differs from our configured page size.
return allPages.reduce((acc, page) => acc + page.length, 0);
},
initialPageParam: 0,
staleTime: 60 * 1000, // 1 minute
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: true,
enabled,
});
// Notify parent when data has loaded
useEffect(() => {
if (isSuccess && !hasCalledOnLoaded.current && onLoaded) {
hasCalledOnLoaded.current = true;
onLoaded();
}
}, [isSuccess, onLoaded]);
const { t } = useTranslation();
// Flatten all pages into a single array
const allItems = data?.pages.flat() || [];
// Flatten all pages into a single array (and de-dupe by Id to avoid UI duplicates)
const allItems = useMemo(() => {
const items = data?.pages.flat() ?? [];
const seen = new Set<string>();
const deduped: BaseItemDto[] = [];
for (const item of items) {
const id = item.Id;
if (!id) continue;
if (seen.has(id)) continue;
seen.add(id);
deduped.push(item);
}
return deduped;
}, [data]);
const snapOffsets = useMemo(() => {
const itemWidth = orientation === "horizontal" ? 184 : 120; // w-44 (176px) + mr-2 (8px) or w-28 (112px) + mr-2 (8px)
@@ -90,9 +129,12 @@ export const InfiniteScrollingCollectionList: React.FC<Props> = ({
return (
<View {...props}>
<Text className='px-4 text-lg font-bold mb-2 text-neutral-100'>
{title}
</Text>
<SectionHeader
title={title}
actionLabel={t("common.seeAll", { defaultValue: "See all" })}
actionDisabled={isLoading}
onPressAction={onPressSeeAll}
/>
{isLoading === false && allItems.length === 0 && (
<View className='px-4'>
<Text className='text-neutral-500'>{t("home.no_items")}</Text>

View File

@@ -0,0 +1,245 @@
import type {
BaseItemDto,
PublicSystemInfo,
} from "@jellyfin/sdk/lib/generated-client/models";
import { getItemsApi, getSystemApi } from "@jellyfin/sdk/lib/utils/api";
import { useQuery } from "@tanstack/react-query";
import { useAtomValue } from "jotai";
import { useMemo } from "react";
import { ScrollView, View, type ViewProps } from "react-native";
import { SectionHeader } from "@/components/common/SectionHeader";
import { Text } from "@/components/common/Text";
import MoviePoster from "@/components/posters/MoviePoster";
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
import { useSettings } from "@/utils/atoms/settings";
import { createStreamystatsApi } from "@/utils/streamystats/api";
import type { StreamystatsWatchlist } from "@/utils/streamystats/types";
import { TouchableItemRouter } from "../common/TouchableItemRouter";
import { ItemCardText } from "../ItemCardText";
import SeriesPoster from "../posters/SeriesPoster";
const ITEM_WIDTH = 120; // w-28 (112px) + mr-2 (8px)
interface WatchlistSectionProps extends ViewProps {
watchlist: StreamystatsWatchlist;
jellyfinServerId: string;
}
const WatchlistSection: React.FC<WatchlistSectionProps> = ({
watchlist,
jellyfinServerId,
...props
}) => {
const api = useAtomValue(apiAtom);
const user = useAtomValue(userAtom);
const { settings } = useSettings();
const { data: items, isLoading } = useQuery({
queryKey: [
"streamystats",
"watchlist",
watchlist.id,
jellyfinServerId,
settings?.streamyStatsServerUrl,
],
queryFn: async (): Promise<BaseItemDto[]> => {
if (!settings?.streamyStatsServerUrl || !api?.accessToken || !user?.Id) {
return [];
}
const streamystatsApi = createStreamystatsApi({
serverUrl: settings.streamyStatsServerUrl,
jellyfinToken: api.accessToken,
});
const watchlistDetail = await streamystatsApi.getWatchlistItemIds({
watchlistId: watchlist.id,
jellyfinServerId,
});
const itemIds = watchlistDetail.data?.items;
if (!itemIds?.length) {
return [];
}
const response = await getItemsApi(api).getItems({
userId: user.Id,
ids: itemIds,
fields: ["PrimaryImageAspectRatio", "Genres"],
enableImageTypes: ["Primary", "Backdrop", "Thumb"],
});
return response.data.Items || [];
},
enabled:
Boolean(settings?.streamyStatsServerUrl) &&
Boolean(api?.accessToken) &&
Boolean(user?.Id),
staleTime: 5 * 60 * 1000,
refetchOnMount: false,
refetchOnWindowFocus: false,
});
const snapOffsets = useMemo(() => {
return items?.map((_, index) => index * ITEM_WIDTH) ?? [];
}, [items]);
if (!isLoading && (!items || items.length === 0)) return null;
return (
<View {...props}>
<SectionHeader title={watchlist.name} />
{isLoading ? (
<View className='flex flex-row gap-2 px-4'>
{[1, 2, 3].map((i) => (
<View className='w-28' key={i}>
<View className='bg-neutral-900 aspect-[2/3] w-full rounded-md mb-1' />
<View className='rounded-md overflow-hidden mb-1 self-start'>
<Text
className='text-neutral-900 bg-neutral-900 rounded-md'
numberOfLines={1}
>
Loading...
</Text>
</View>
</View>
))}
</View>
) : (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
snapToOffsets={snapOffsets}
decelerationRate='fast'
>
<View className='px-4 flex flex-row'>
{items?.map((item) => (
<TouchableItemRouter
item={item}
key={item.Id}
className='mr-2 w-28'
>
{item.Type === "Movie" && <MoviePoster item={item} />}
{item.Type === "Series" && <SeriesPoster item={item} />}
<ItemCardText item={item} />
</TouchableItemRouter>
))}
</View>
</ScrollView>
)}
</View>
);
};
interface StreamystatsPromotedWatchlistsProps extends ViewProps {
enabled?: boolean;
}
export const StreamystatsPromotedWatchlists: React.FC<
StreamystatsPromotedWatchlistsProps
> = ({ enabled = true, ...props }) => {
const api = useAtomValue(apiAtom);
const user = useAtomValue(userAtom);
const { settings } = useSettings();
const streamyStatsEnabled = useMemo(() => {
return Boolean(settings?.streamyStatsServerUrl);
}, [settings?.streamyStatsServerUrl]);
// Fetch server info to get the Jellyfin server ID
const { data: serverInfo } = useQuery({
queryKey: ["jellyfin", "serverInfo"],
queryFn: async (): Promise<PublicSystemInfo | null> => {
if (!api) return null;
const response = await getSystemApi(api).getPublicSystemInfo();
return response.data;
},
enabled: enabled && Boolean(api) && streamyStatsEnabled,
staleTime: 60 * 60 * 1000,
});
const jellyfinServerId = serverInfo?.Id;
const {
data: watchlists,
isLoading,
isError,
} = useQuery({
queryKey: [
"streamystats",
"promotedWatchlists",
jellyfinServerId,
settings?.streamyStatsServerUrl,
],
queryFn: async (): Promise<StreamystatsWatchlist[]> => {
if (
!settings?.streamyStatsServerUrl ||
!api?.accessToken ||
!jellyfinServerId
) {
return [];
}
const streamystatsApi = createStreamystatsApi({
serverUrl: settings.streamyStatsServerUrl,
jellyfinToken: api.accessToken,
});
const response = await streamystatsApi.getPromotedWatchlists({
jellyfinServerId,
includePreview: false,
});
return response.data || [];
},
enabled:
enabled &&
streamyStatsEnabled &&
Boolean(api?.accessToken) &&
Boolean(jellyfinServerId) &&
Boolean(user?.Id),
staleTime: 5 * 60 * 1000,
refetchOnMount: false,
refetchOnWindowFocus: false,
});
if (!streamyStatsEnabled) return null;
if (isError) return null;
if (!isLoading && (!watchlists || watchlists.length === 0)) return null;
if (isLoading) {
return (
<View {...props}>
<View className='h-4 w-32 bg-neutral-900 rounded ml-4 mb-2' />
<View className='flex flex-row gap-2 px-4'>
{[1, 2, 3].map((i) => (
<View className='w-28' key={i}>
<View className='bg-neutral-900 aspect-[2/3] w-full rounded-md mb-1' />
<View className='rounded-md overflow-hidden mb-1 self-start'>
<Text
className='text-neutral-900 bg-neutral-900 rounded-md'
numberOfLines={1}
>
Loading...
</Text>
</View>
</View>
))}
</View>
</View>
);
}
return (
<>
{watchlists?.map((watchlist) => (
<WatchlistSection
key={watchlist.id}
watchlist={watchlist}
jellyfinServerId={jellyfinServerId!}
{...props}
/>
))}
</>
);
};

View File

@@ -0,0 +1,197 @@
import type {
BaseItemDto,
PublicSystemInfo,
} from "@jellyfin/sdk/lib/generated-client/models";
import { getItemsApi, getSystemApi } from "@jellyfin/sdk/lib/utils/api";
import { useQuery } from "@tanstack/react-query";
import { useAtomValue } from "jotai";
import { useMemo } from "react";
import { ScrollView, View, type ViewProps } from "react-native";
import { SectionHeader } from "@/components/common/SectionHeader";
import { Text } from "@/components/common/Text";
import MoviePoster from "@/components/posters/MoviePoster";
import { apiAtom, userAtom } from "@/providers/JellyfinProvider";
import { useSettings } from "@/utils/atoms/settings";
import { createStreamystatsApi } from "@/utils/streamystats/api";
import type { StreamystatsRecommendationsIdsResponse } from "@/utils/streamystats/types";
import { TouchableItemRouter } from "../common/TouchableItemRouter";
import { ItemCardText } from "../ItemCardText";
import SeriesPoster from "../posters/SeriesPoster";
const ITEM_WIDTH = 120; // w-28 (112px) + mr-2 (8px)
interface Props extends ViewProps {
title: string;
type: "Movie" | "Series";
limit?: number;
enabled?: boolean;
}
export const StreamystatsRecommendations: React.FC<Props> = ({
title,
type,
limit = 20,
enabled = true,
...props
}) => {
const api = useAtomValue(apiAtom);
const user = useAtomValue(userAtom);
const { settings } = useSettings();
const streamyStatsEnabled = useMemo(() => {
return Boolean(settings?.streamyStatsServerUrl);
}, [settings?.streamyStatsServerUrl]);
// Fetch server info to get the Jellyfin server ID
const { data: serverInfo } = useQuery({
queryKey: ["jellyfin", "serverInfo"],
queryFn: async (): Promise<PublicSystemInfo | null> => {
if (!api) return null;
const response = await getSystemApi(api).getPublicSystemInfo();
return response.data;
},
enabled: enabled && Boolean(api) && streamyStatsEnabled,
staleTime: 60 * 60 * 1000, // 1 hour - server info rarely changes
});
const jellyfinServerId = serverInfo?.Id;
const {
data: recommendationIds,
isLoading: isLoadingRecommendations,
isError: isRecommendationsError,
} = useQuery({
queryKey: [
"streamystats",
"recommendations",
type,
jellyfinServerId,
settings?.streamyStatsServerUrl,
],
queryFn: async (): Promise<string[]> => {
if (
!settings?.streamyStatsServerUrl ||
!api?.accessToken ||
!jellyfinServerId
) {
return [];
}
const streamyStatsApi = createStreamystatsApi({
serverUrl: settings.streamyStatsServerUrl,
jellyfinToken: api.accessToken,
});
const response = await streamyStatsApi.getRecommendationIds(
jellyfinServerId,
type,
limit,
);
const data = response as StreamystatsRecommendationsIdsResponse;
if (type === "Movie") {
return data.data.movies || [];
}
return data.data.series || [];
},
enabled:
enabled &&
streamyStatsEnabled &&
Boolean(api?.accessToken) &&
Boolean(jellyfinServerId) &&
Boolean(user?.Id),
staleTime: 5 * 60 * 1000, // 5 minutes
refetchOnMount: false,
refetchOnWindowFocus: false,
});
const {
data: items,
isLoading: isLoadingItems,
isError: isItemsError,
} = useQuery({
queryKey: [
"streamystats",
"recommendations",
"items",
type,
recommendationIds,
],
queryFn: async (): Promise<BaseItemDto[]> => {
if (!api || !user?.Id || !recommendationIds?.length) {
return [];
}
const response = await getItemsApi(api).getItems({
userId: user.Id,
ids: recommendationIds,
fields: ["PrimaryImageAspectRatio", "Genres"],
enableImageTypes: ["Primary", "Backdrop", "Thumb"],
});
return response.data.Items || [];
},
enabled:
Boolean(recommendationIds?.length) && Boolean(api) && Boolean(user?.Id),
staleTime: 5 * 60 * 1000,
refetchOnMount: false,
refetchOnWindowFocus: false,
});
const isLoading = isLoadingRecommendations || isLoadingItems;
const isError = isRecommendationsError || isItemsError;
const snapOffsets = useMemo(() => {
return items?.map((_, index) => index * ITEM_WIDTH) ?? [];
}, [items]);
if (!streamyStatsEnabled) return null;
if (isError) return null;
if (!isLoading && (!items || items.length === 0)) return null;
return (
<View {...props}>
<SectionHeader title={title} />
{isLoading ? (
<View className='flex flex-row gap-2 px-4'>
{[1, 2, 3].map((i) => (
<View className='w-28' key={i}>
<View className='bg-neutral-900 aspect-[2/3] w-full rounded-md mb-1' />
<View className='rounded-md overflow-hidden mb-1 self-start'>
<Text
className='text-neutral-900 bg-neutral-900 rounded-md'
numberOfLines={1}
>
Loading title...
</Text>
</View>
</View>
))}
</View>
) : (
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
snapToOffsets={snapOffsets}
decelerationRate='fast'
>
<View className='px-4 flex flex-row'>
{items?.map((item) => (
<TouchableItemRouter
item={item}
key={item.Id}
className='mr-2 w-28'
>
{item.Type === "Movie" && <MoviePoster item={item} />}
{item.Type === "Series" && <SeriesPoster item={item} />}
<ItemCardText item={item} />
</TouchableItemRouter>
))}
</View>
</ScrollView>
)}
</View>
);
};

View File

@@ -0,0 +1,80 @@
import type {
BaseItemDto,
BaseItemPerson,
} from "@jellyfin/sdk/lib/generated-client/models";
import type React from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { InteractionManager, View, type ViewProps } from "react-native";
import { MoreMoviesWithActor } from "@/components/MoreMoviesWithActor";
import { CastAndCrew } from "@/components/series/CastAndCrew";
import { useItemPeopleQuery } from "@/hooks/useItemPeopleQuery";
interface Props extends ViewProps {
item: BaseItemDto;
isOffline: boolean;
}
export const ItemPeopleSections: React.FC<Props> = ({
item,
isOffline,
...props
}) => {
const [enabled, setEnabled] = useState(false);
useEffect(() => {
if (isOffline) return;
const task = InteractionManager.runAfterInteractions(() =>
setEnabled(true),
);
return () => task.cancel();
}, [isOffline]);
const { data, isLoading } = useItemPeopleQuery(
item.Id,
enabled && !isOffline,
);
const people = useMemo(() => (Array.isArray(data) ? data : []), [data]);
const itemWithPeople = useMemo(() => {
return { ...item, People: people } as BaseItemDto;
}, [item, people]);
const topPeople = useMemo(() => people.slice(0, 3), [people]);
const renderActorSection = useCallback(
(person: BaseItemPerson, idx: number, total: number) => {
if (!person.Id) return null;
const spacingClassName = idx === total - 1 ? undefined : "mb-2";
return (
<MoreMoviesWithActor
key={person.Id}
currentItem={item}
actorId={person.Id}
actorName={person.Name}
className={spacingClassName}
/>
);
},
[item],
);
if (isOffline || !enabled) return null;
const shouldSpaceCastAndCrew = topPeople.length > 0;
return (
<View {...props}>
<CastAndCrew
item={itemWithPeople}
loading={isLoading}
className={shouldSpaceCastAndCrew ? "mb-2" : undefined}
/>
{topPeople.map((person, idx) =>
renderActorSection(person, idx, topPeople.length),
)}
</View>
);
};

View File

@@ -6,6 +6,7 @@ import { Text } from "../common/Text";
interface Props extends ViewProps {
title?: string | null | undefined;
subtitle?: string | null | undefined;
subtitleColor?: "default" | "red";
value?: string | null | undefined;
children?: ReactNode;
iconAfter?: ReactNode;
@@ -14,6 +15,7 @@ interface Props extends ViewProps {
textColor?: "default" | "blue" | "red";
onPress?: () => void;
disabled?: boolean;
disabledByAdmin?: boolean;
}
export const ListItem: React.FC<PropsWithChildren<Props>> = ({
@@ -27,21 +29,23 @@ export const ListItem: React.FC<PropsWithChildren<Props>> = ({
textColor = "default",
onPress,
disabled = false,
disabledByAdmin = false,
...viewProps
}) => {
const effectiveSubtitle = disabledByAdmin ? "Disabled by admin" : subtitle;
const isDisabled = disabled || disabledByAdmin;
if (onPress)
return (
<TouchableOpacity
disabled={disabled}
disabled={isDisabled}
onPress={onPress}
className={`flex flex-row items-center justify-between bg-neutral-900 min-h-[42px] py-2 pr-4 pl-4 ${
disabled ? "opacity-50" : ""
}`}
className={`flex flex-row items-center justify-between bg-neutral-900 min-h-[42px] py-2 pr-4 pl-4 ${isDisabled ? "opacity-50" : ""}`}
{...(viewProps as any)}
>
<ListItemContent
title={title}
subtitle={subtitle}
subtitle={effectiveSubtitle}
subtitleColor={disabledByAdmin ? "red" : undefined}
value={value}
icon={icon}
textColor={textColor}
@@ -54,14 +58,13 @@ export const ListItem: React.FC<PropsWithChildren<Props>> = ({
);
return (
<View
className={`flex flex-row items-center justify-between bg-neutral-900 min-h-[42px] py-2 pr-4 pl-4 ${
disabled ? "opacity-50" : ""
}`}
className={`flex flex-row items-center justify-between bg-neutral-900 min-h-[42px] py-2 pr-4 pl-4 ${isDisabled ? "opacity-50" : ""}`}
{...viewProps}
>
<ListItemContent
title={title}
subtitle={subtitle}
subtitle={effectiveSubtitle}
subtitleColor={disabledByAdmin ? "red" : undefined}
value={value}
icon={icon}
textColor={textColor}
@@ -77,6 +80,7 @@ export const ListItem: React.FC<PropsWithChildren<Props>> = ({
const ListItemContent = ({
title,
subtitle,
subtitleColor,
textColor,
icon,
value,
@@ -107,7 +111,7 @@ const ListItemContent = ({
</Text>
{subtitle && (
<Text
className='text-[#9899A1] text-[12px] mt-0.5'
className={`text-[12px] mt-0.5 ${subtitleColor === "red" ? "text-red-600" : "text-[#9899A1]"}`}
numberOfLines={2}
>
{subtitle}

View File

@@ -0,0 +1,236 @@
import { Ionicons } from "@expo/vector-icons";
import { BlurView } from "expo-blur";
import { Image } from "expo-image";
import { useRouter } from "expo-router";
import { useAtom } from "jotai";
import React, { useCallback, useMemo } from "react";
import { Platform, StyleSheet, TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Text } from "@/components/common/Text";
import { apiAtom } from "@/providers/JellyfinProvider";
import { useMusicPlayer } from "@/providers/MusicPlayerProvider";
const HORIZONTAL_MARGIN = Platform.OS === "android" ? 8 : 16;
const BOTTOM_TAB_HEIGHT = Platform.OS === "android" ? 56 : 52;
const BAR_HEIGHT = Platform.OS === "android" ? 58 : 50;
export const MiniPlayerBar: React.FC = () => {
const [api] = useAtom(apiAtom);
const insets = useSafeAreaInsets();
const router = useRouter();
const { currentTrack, isPlaying, progress, duration, togglePlayPause, next } =
useMusicPlayer();
const imageUrl = useMemo(() => {
if (!api || !currentTrack) return null;
const albumId = currentTrack.AlbumId || currentTrack.ParentId;
if (albumId) {
return `${api.basePath}/Items/${albumId}/Images/Primary?maxHeight=100&maxWidth=100`;
}
return `${api.basePath}/Items/${currentTrack.Id}/Images/Primary?maxHeight=100&maxWidth=100`;
}, [api, currentTrack]);
const _progressPercentage = useMemo(() => {
if (!duration || duration === 0) return 0;
return (progress / duration) * 100;
}, [progress, duration]);
const handlePress = useCallback(() => {
router.push("/(auth)/now-playing");
}, [router]);
const handlePlayPause = useCallback(
(e: any) => {
e.stopPropagation();
togglePlayPause();
},
[togglePlayPause],
);
const handleNext = useCallback(
(e: any) => {
e.stopPropagation();
next();
},
[next],
);
if (!currentTrack) return null;
const content = (
<>
{/* Album art */}
<View style={styles.albumArt}>
{imageUrl ? (
<Image
source={{ uri: imageUrl }}
style={styles.albumImage}
contentFit='cover'
cachePolicy='memory-disk'
/>
) : (
<View style={styles.albumPlaceholder}>
<Ionicons name='musical-note' size={20} color='#888' />
</View>
)}
</View>
{/* Track info */}
<View style={styles.trackInfo}>
<Text numberOfLines={1} style={styles.trackTitle}>
{currentTrack.Name}
</Text>
<Text numberOfLines={1} style={styles.artistName}>
{currentTrack.Artists?.join(", ") || currentTrack.AlbumArtist}
</Text>
</View>
{/* Controls */}
<View style={styles.controls}>
<TouchableOpacity
onPress={handlePlayPause}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
style={styles.controlButton}
>
<Ionicons
name={isPlaying ? "pause" : "play"}
size={26}
color='white'
/>
</TouchableOpacity>
<TouchableOpacity
onPress={handleNext}
hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
style={styles.controlButton}
>
<Ionicons name='play-forward' size={22} color='white' />
</TouchableOpacity>
</View>
{/* Progress bar at bottom */}
{/* <View style={styles.progressContainer}>
<View
style={[styles.progressFill, { width: `${progressPercentage}%` }]}
/>
</View> */}
</>
);
return (
<View
style={[
styles.container,
{
bottom:
BOTTOM_TAB_HEIGHT +
insets.bottom +
(Platform.OS === "android" ? 32 : 4),
},
]}
>
<TouchableOpacity
onPress={handlePress}
activeOpacity={0.9}
style={styles.touchable}
>
{Platform.OS === "ios" ? (
<BlurView intensity={80} tint='dark' style={styles.blurContainer}>
{content}
</BlurView>
) : (
<View style={styles.androidContainer}>{content}</View>
)}
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
position: "absolute",
left: HORIZONTAL_MARGIN,
right: HORIZONTAL_MARGIN,
shadowColor: "#000",
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 8,
},
touchable: {
borderRadius: 50,
overflow: "hidden",
},
blurContainer: {
flexDirection: "row",
alignItems: "center",
paddingRight: 10,
paddingLeft: 20,
paddingVertical: 0,
height: BAR_HEIGHT,
backgroundColor: "rgba(40, 40, 40, 0.5)",
},
androidContainer: {
flexDirection: "row",
alignItems: "center",
paddingHorizontal: 10,
paddingVertical: 8,
height: BAR_HEIGHT,
backgroundColor: "rgba(28, 28, 30, 0.97)",
borderRadius: 14,
borderWidth: 0.5,
borderColor: "rgba(255, 255, 255, 0.1)",
},
albumArt: {
width: 32,
height: 32,
borderRadius: 8,
overflow: "hidden",
backgroundColor: "#333",
},
albumImage: {
width: "100%",
height: "100%",
},
albumPlaceholder: {
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#2a2a2a",
},
trackInfo: {
flex: 1,
marginLeft: 12,
marginRight: 8,
justifyContent: "center",
},
trackTitle: {
color: "white",
fontSize: 14,
fontWeight: "600",
},
artistName: {
color: "rgba(255, 255, 255, 0.6)",
fontSize: 12,
},
controls: {
flexDirection: "row",
alignItems: "center",
},
controlButton: {
padding: 8,
},
progressContainer: {
position: "absolute",
bottom: 0,
left: 10,
right: 10,
height: 3,
backgroundColor: "rgba(255, 255, 255, 0.15)",
borderRadius: 1.5,
},
progressFill: {
height: "100%",
backgroundColor: "white",
borderRadius: 1.5,
},
});

View File

@@ -0,0 +1,68 @@
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
import { Image } from "expo-image";
import { useRouter } from "expo-router";
import { useAtom } from "jotai";
import React, { useCallback, useMemo } from "react";
import { TouchableOpacity, View } from "react-native";
import { Text } from "@/components/common/Text";
import { apiAtom } from "@/providers/JellyfinProvider";
import { getPrimaryImageUrl } from "@/utils/jellyfin/image/getPrimaryImageUrl";
interface Props {
album: BaseItemDto;
width?: number;
}
export const MusicAlbumCard: React.FC<Props> = ({ album, width = 150 }) => {
const [api] = useAtom(apiAtom);
const router = useRouter();
const imageUrl = useMemo(
() => getPrimaryImageUrl({ api, item: album }),
[api, album],
);
const handlePress = useCallback(() => {
router.push({
pathname: "/music/album/[albumId]",
params: { albumId: album.Id! },
});
}, [router, album.Id]);
return (
<TouchableOpacity
onPress={handlePress}
style={{ width }}
className='flex flex-col'
>
<View
style={{
width,
height: width,
borderRadius: 8,
overflow: "hidden",
backgroundColor: "#1a1a1a",
}}
>
{imageUrl ? (
<Image
source={{ uri: imageUrl }}
style={{ width: "100%", height: "100%" }}
contentFit='cover'
cachePolicy='memory-disk'
/>
) : (
<View className='flex-1 items-center justify-center bg-neutral-800'>
<Text className='text-4xl'>🎵</Text>
</View>
)}
</View>
<Text numberOfLines={1} className='text-white text-sm font-medium mt-2'>
{album.Name}
</Text>
<Text numberOfLines={1} className='text-neutral-400 text-xs'>
{album.AlbumArtist || album.Artists?.join(", ")}
</Text>
</TouchableOpacity>
);
};

View File

@@ -0,0 +1,68 @@
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
import { Image } from "expo-image";
import { useRouter } from "expo-router";
import { useAtom } from "jotai";
import React, { useCallback, useMemo } from "react";
import { TouchableOpacity, View } from "react-native";
import { Text } from "@/components/common/Text";
import { apiAtom } from "@/providers/JellyfinProvider";
import { getPrimaryImageUrl } from "@/utils/jellyfin/image/getPrimaryImageUrl";
interface Props {
artist: BaseItemDto;
size?: number;
}
export const MusicArtistCard: React.FC<Props> = ({ artist, size = 100 }) => {
const [api] = useAtom(apiAtom);
const router = useRouter();
const imageUrl = useMemo(
() => getPrimaryImageUrl({ api, item: artist }),
[api, artist],
);
const handlePress = useCallback(() => {
router.push({
pathname: "/music/artist/[artistId]",
params: { artistId: artist.Id! },
});
}, [router, artist.Id]);
return (
<TouchableOpacity
onPress={handlePress}
style={{ width: size }}
className='flex flex-col items-center'
>
<View
style={{
width: size,
height: size,
borderRadius: size / 2,
overflow: "hidden",
backgroundColor: "#1a1a1a",
}}
>
{imageUrl ? (
<Image
source={{ uri: imageUrl }}
style={{ width: "100%", height: "100%" }}
contentFit='cover'
cachePolicy='memory-disk'
/>
) : (
<View className='flex-1 items-center justify-center bg-neutral-800'>
<Text className='text-3xl'>👤</Text>
</View>
)}
</View>
<Text
numberOfLines={2}
className='text-white text-xs font-medium mt-2 text-center'
>
{artist.Name}
</Text>
</TouchableOpacity>
);
};

View File

@@ -0,0 +1,83 @@
import { useEffect, useRef } from "react";
import TrackPlayer, {
Event,
type PlaybackActiveTrackChangedEvent,
State,
useActiveTrack,
usePlaybackState,
useProgress,
} from "react-native-track-player";
import { useMusicPlayer } from "@/providers/MusicPlayerProvider";
export const MusicPlaybackEngine: React.FC = () => {
const { position, duration } = useProgress(1000);
const playbackState = usePlaybackState();
const activeTrack = useActiveTrack();
const {
setProgress,
setDuration,
setIsPlaying,
reportProgress,
onTrackEnd,
syncFromTrackPlayer,
} = useMusicPlayer();
const lastReportedProgressRef = useRef(0);
// Sync progress from TrackPlayer to our state
useEffect(() => {
if (position > 0) {
setProgress(position);
}
}, [position, setProgress]);
// Sync duration from TrackPlayer to our state
useEffect(() => {
if (duration > 0) {
setDuration(duration);
}
}, [duration, setDuration]);
// Sync playback state from TrackPlayer to our state
useEffect(() => {
const isPlaying = playbackState.state === State.Playing;
setIsPlaying(isPlaying);
}, [playbackState.state, setIsPlaying]);
// Sync active track changes
useEffect(() => {
if (activeTrack) {
syncFromTrackPlayer();
}
}, [activeTrack?.id, syncFromTrackPlayer]);
// Report progress every ~10 seconds
useEffect(() => {
if (
Math.floor(position) - Math.floor(lastReportedProgressRef.current) >=
10
) {
lastReportedProgressRef.current = position;
reportProgress();
}
}, [position, reportProgress]);
// Listen for track end
useEffect(() => {
const subscription =
TrackPlayer.addEventListener<PlaybackActiveTrackChangedEvent>(
Event.PlaybackActiveTrackChanged,
async (event) => {
// If there's no next track and the previous track ended, call onTrackEnd
if (event.lastTrack && !event.track) {
onTrackEnd();
}
},
);
return () => subscription.remove();
}, [onTrackEnd]);
// No visual component needed - TrackPlayer is headless
return null;
};

View File

@@ -0,0 +1,71 @@
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
import { Image } from "expo-image";
import { useRouter } from "expo-router";
import { useAtom } from "jotai";
import React, { useCallback, useMemo } from "react";
import { TouchableOpacity, View } from "react-native";
import { Text } from "@/components/common/Text";
import { apiAtom } from "@/providers/JellyfinProvider";
import { getPrimaryImageUrl } from "@/utils/jellyfin/image/getPrimaryImageUrl";
interface Props {
playlist: BaseItemDto;
width?: number;
}
export const MusicPlaylistCard: React.FC<Props> = ({
playlist,
width = 150,
}) => {
const [api] = useAtom(apiAtom);
const router = useRouter();
const imageUrl = useMemo(
() => getPrimaryImageUrl({ api, item: playlist }),
[api, playlist],
);
const handlePress = useCallback(() => {
router.push({
pathname: "/music/playlist/[playlistId]",
params: { playlistId: playlist.Id! },
});
}, [router, playlist.Id]);
return (
<TouchableOpacity
onPress={handlePress}
style={{ width }}
className='flex flex-col'
>
<View
style={{
width,
height: width,
borderRadius: 8,
overflow: "hidden",
backgroundColor: "#1a1a1a",
}}
>
{imageUrl ? (
<Image
source={{ uri: imageUrl }}
style={{ width: "100%", height: "100%" }}
contentFit='cover'
cachePolicy='memory-disk'
/>
) : (
<View className='flex-1 items-center justify-center bg-neutral-800'>
<Text className='text-4xl'>🎶</Text>
</View>
)}
</View>
<Text numberOfLines={1} className='text-white text-sm font-medium mt-2'>
{playlist.Name}
</Text>
<Text numberOfLines={1} className='text-neutral-400 text-xs'>
{playlist.ChildCount} tracks
</Text>
</TouchableOpacity>
);
};

View File

@@ -0,0 +1,130 @@
import { useActionSheet } from "@expo/react-native-action-sheet";
import { Ionicons } from "@expo/vector-icons";
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
import { Image } from "expo-image";
import { useAtom } from "jotai";
import React, { useCallback, useMemo } from "react";
import { TouchableOpacity, View } from "react-native";
import { Text } from "@/components/common/Text";
import { apiAtom } from "@/providers/JellyfinProvider";
import { useMusicPlayer } from "@/providers/MusicPlayerProvider";
import { getPrimaryImageUrl } from "@/utils/jellyfin/image/getPrimaryImageUrl";
import { formatDuration } from "@/utils/time";
interface Props {
track: BaseItemDto;
index?: number;
queue?: BaseItemDto[];
showArtwork?: boolean;
}
export const MusicTrackItem: React.FC<Props> = ({
track,
index,
queue,
showArtwork = true,
}) => {
const [api] = useAtom(apiAtom);
const { showActionSheetWithOptions } = useActionSheet();
const { playTrack, playNext, addToQueue, currentTrack, isPlaying } =
useMusicPlayer();
const imageUrl = useMemo(() => {
const albumId = track.AlbumId || track.ParentId;
if (albumId) {
return `${api?.basePath}/Items/${albumId}/Images/Primary?maxHeight=100&maxWidth=100`;
}
return getPrimaryImageUrl({ api, item: track });
}, [api, track]);
const isCurrentTrack = currentTrack?.Id === track.Id;
const duration = useMemo(() => {
if (!track.RunTimeTicks) return "";
return formatDuration(track.RunTimeTicks);
}, [track.RunTimeTicks]);
const handlePress = useCallback(() => {
playTrack(track, queue);
}, [playTrack, track, queue]);
const handleLongPress = useCallback(() => {
const options = ["Play Next", "Add to Queue", "Cancel"];
const cancelButtonIndex = 2;
showActionSheetWithOptions(
{
options,
cancelButtonIndex,
title: track.Name ?? undefined,
message: (track.Artists?.join(", ") || track.AlbumArtist) ?? undefined,
},
(selectedIndex) => {
if (selectedIndex === 0) {
playNext(track);
} else if (selectedIndex === 1) {
addToQueue(track);
}
},
);
}, [showActionSheetWithOptions, track, playNext, addToQueue]);
return (
<TouchableOpacity
onPress={handlePress}
onLongPress={handleLongPress}
delayLongPress={300}
className={`flex flex-row items-center py-3 ${isCurrentTrack ? "bg-purple-900/20" : ""}`}
>
{index !== undefined && (
<View className='w-8 items-center'>
{isCurrentTrack && isPlaying ? (
<Ionicons name='musical-note' size={16} color='#9334E9' />
) : (
<Text className='text-neutral-500 text-sm'>{index}</Text>
)}
</View>
)}
{showArtwork && (
<View
style={{
width: 48,
height: 48,
borderRadius: 4,
overflow: "hidden",
backgroundColor: "#1a1a1a",
marginRight: 12,
}}
>
{imageUrl ? (
<Image
source={{ uri: imageUrl }}
style={{ width: "100%", height: "100%" }}
contentFit='cover'
cachePolicy='memory-disk'
/>
) : (
<View className='flex-1 items-center justify-center bg-neutral-800'>
<Ionicons name='musical-note' size={20} color='#737373' />
</View>
)}
</View>
)}
<View className='flex-1 mr-4'>
<Text
numberOfLines={1}
className={`text-sm ${isCurrentTrack ? "text-purple-400 font-medium" : "text-white"}`}
>
{track.Name}
</Text>
<Text numberOfLines={1} className='text-neutral-400 text-xs mt-0.5'>
{track.Artists?.join(", ") || track.AlbumArtist}
</Text>
</View>
<Text className='text-neutral-500 text-xs'>{duration}</Text>
</TouchableOpacity>
);
};

View File

@@ -0,0 +1,6 @@
export * from "./MiniPlayerBar";
export * from "./MusicAlbumCard";
export * from "./MusicArtistCard";
export * from "./MusicPlaybackEngine";
export * from "./MusicPlaylistCard";
export * from "./MusicTrackItem";

View File

@@ -8,6 +8,7 @@ import type React from "react";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { TouchableOpacity, View, type ViewProps } from "react-native";
import { POSTER_CAROUSEL_HEIGHT } from "@/constants/Values";
import { apiAtom } from "@/providers/JellyfinProvider";
import { getPrimaryImageUrl } from "@/utils/jellyfin/image/getPrimaryImageUrl";
import { HorizontalScroll } from "../common/HorizontalScroll";
@@ -50,7 +51,7 @@ export const CastAndCrew: React.FC<Props> = ({ item, loading, ...props }) => {
<HorizontalScroll
loading={loading}
keyExtractor={(i, _idx) => i.Id?.toString() || ""}
height={247}
height={POSTER_CAROUSEL_HEIGHT}
data={destinctPeople}
renderItem={(i) => (
<TouchableOpacity
@@ -65,8 +66,12 @@ export const CastAndCrew: React.FC<Props> = ({ item, loading, ...props }) => {
className='flex flex-col w-28'
>
<Poster id={i.Id} url={getPrimaryImageUrl({ api, item: i })} />
<Text className='mt-2'>{i.Name}</Text>
<Text className='text-xs opacity-50'>{i.Role}</Text>
<Text className='mt-2' numberOfLines={1}>
{i.Name}
</Text>
<Text className='text-xs opacity-50' numberOfLines={1}>
{i.Role}
</Text>
</TouchableOpacity>
)}
/>

View File

@@ -4,6 +4,7 @@ import { useAtom } from "jotai";
import type React from "react";
import { useTranslation } from "react-i18next";
import { TouchableOpacity, View, type ViewProps } from "react-native";
import { POSTER_CAROUSEL_HEIGHT } from "@/constants/Values";
import { apiAtom } from "@/providers/JellyfinProvider";
import { getPrimaryImageUrlById } from "@/utils/jellyfin/image/getPrimaryImageUrlById";
import { HorizontalScroll } from "../common/HorizontalScroll";
@@ -25,7 +26,7 @@ export const CurrentSeries: React.FC<Props> = ({ item, ...props }) => {
</Text>
<HorizontalScroll
data={[item]}
height={247}
height={POSTER_CAROUSEL_HEIGHT}
renderItem={(item, _index) => (
<TouchableOpacity
key={item?.Id}
@@ -38,7 +39,7 @@ export const CurrentSeries: React.FC<Props> = ({ item, ...props }) => {
id={item?.Id}
url={getPrimaryImageUrlById({ api, id: item?.ParentId })}
/>
<Text>{item?.SeriesName}</Text>
<Text numberOfLines={1}>{item?.SeriesName}</Text>
</TouchableOpacity>
)}
/>

View File

@@ -50,6 +50,16 @@ export const AppearanceSettings: React.FC = () => {
}
/>
</ListItem>
<ListItem
title={t("home.settings.appearance.merge_next_up_continue_watching")}
>
<Switch
value={settings.mergeNextUpAndContinueWatching}
onValueChange={(value) =>
updateSettings({ mergeNextUpAndContinueWatching: value })
}
/>
</ListItem>
<ListItem
onPress={() =>
router.push("/settings/appearance/hide-libraries/page")

View File

@@ -11,12 +11,12 @@ const DisabledSetting: React.FC<
}}
>
<View {...props}>
{children}
{disabled && showText && (
<Text className='text-center text-red-700 my-4'>
{text ?? "Currently disabled by admin."}
<Text className='text-xs text-red-600 px-4 mt-1'>
{text ?? "Disabled by admin"}
</Text>
)}
{children}
</View>
</View>
);

View File

@@ -0,0 +1,40 @@
import type React from "react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Platform, Switch } from "react-native";
import { setHardwareDecode } from "@/modules/sf-player";
import { useSettings } from "@/utils/atoms/settings";
import { ListGroup } from "../list/ListGroup";
import { ListItem } from "../list/ListItem";
export const KSPlayerSettings: React.FC = () => {
const { settings, updateSettings } = useSettings();
const { t } = useTranslation();
const handleHardwareDecodeChange = useCallback(
(value: boolean) => {
updateSettings({ ksHardwareDecode: value });
setHardwareDecode(value);
},
[updateSettings],
);
if (Platform.OS !== "ios" || !settings) return null;
return (
<ListGroup
title={t("home.settings.subtitles.ksplayer_title")}
className='mt-4'
>
<ListItem
title={t("home.settings.subtitles.hardware_decode")}
subtitle={t("home.settings.subtitles.hardware_decode_description")}
>
<Switch
value={settings.ksHardwareDecode}
onValueChange={handleHardwareDecodeChange}
/>
</ListItem>
</ListGroup>
);
};

View File

@@ -0,0 +1,33 @@
import { useTranslation } from "react-i18next";
import { Switch, Text, View } from "react-native";
import { useSettings } from "@/utils/atoms/settings";
export const KefinTweaksSettings = () => {
const { settings, updateSettings } = useSettings();
const { t } = useTranslation();
const isEnabled = settings?.useKefinTweaks ?? false;
return (
<View className=''>
<View className='flex flex-col rounded-xl overflow-hidden p-4 bg-neutral-900'>
<Text className='text-xs text-red-600 mb-2'>
{t("home.settings.plugins.kefinTweaks.watchlist_enabler")}
</Text>
<View className='flex flex-row items-center justify-between mt-2'>
<Text className='text-white'>
{isEnabled ? t("Watchlist On") : t("Watchlist Off")}
</Text>
<Switch
value={isEnabled}
onValueChange={(value) => updateSettings({ useKefinTweaks: value })}
trackColor={{ false: "#555", true: "purple" }}
thumbColor={isEnabled ? "#fff" : "#ccc"}
/>
</View>
</View>
</View>
);
};

View File

@@ -12,6 +12,7 @@ import { ScreenOrientationEnum, useSettings } from "@/utils/atoms/settings";
import { Text } from "../common/Text";
import { ListGroup } from "../list/ListGroup";
import { ListItem } from "../list/ListItem";
import { VideoPlayerSettings } from "./VideoPlayerSettings";
export const PlaybackControlsSettings: React.FC = () => {
const { settings, updateSettings, pluginSettings } = useSettings();
@@ -190,6 +191,8 @@ export const PlaybackControlsSettings: React.FC = () => {
/>
</ListItem>
</ListGroup>
<VideoPlayerSettings />
</DisabledSetting>
);
};

View File

@@ -28,6 +28,16 @@ export const PluginSettings = () => {
title='Marlin Search'
showArrow
/>
<ListItem
onPress={() => router.push("/settings/plugins/streamystats/page")}
title='Streamystats'
showArrow
/>
<ListItem
onPress={() => router.push("/settings/plugins/kefinTweaks/page")}
title='KefinTweaks'
showArrow
/>
</ListGroup>
);
};

View File

@@ -5,12 +5,6 @@ import { useTranslation } from "react-i18next";
import { Platform, View, type ViewProps } from "react-native";
import { Switch } from "react-native-gesture-handler";
import { Stepper } from "@/components/inputs/Stepper";
import {
OUTLINE_THICKNESS,
type OutlineThickness,
VLC_COLORS,
type VLCColor,
} from "@/constants/SubtitleConstants";
import { useSettings } from "@/utils/atoms/settings";
import { Text } from "../common/Text";
import { ListGroup } from "../list/ListGroup";
@@ -92,84 +86,6 @@ export const SubtitleToggles: React.FC<Props> = ({ ...props }) => {
];
}, [settings?.subtitleMode, t, updateSettings]);
const textColorOptionGroups = useMemo(() => {
const colors = Object.keys(VLC_COLORS) as VLCColor[];
const options = colors.map((color) => ({
type: "radio" as const,
label: t(`home.settings.subtitles.colors.${color}`),
value: color,
selected: (settings?.vlcTextColor || "White") === color,
onPress: () => updateSettings({ vlcTextColor: color }),
}));
return [{ options }];
}, [settings?.vlcTextColor, t, updateSettings]);
const backgroundColorOptionGroups = useMemo(() => {
const colors = Object.keys(VLC_COLORS) as VLCColor[];
const options = colors.map((color) => ({
type: "radio" as const,
label: t(`home.settings.subtitles.colors.${color}`),
value: color,
selected: (settings?.vlcBackgroundColor || "Black") === color,
onPress: () => updateSettings({ vlcBackgroundColor: color }),
}));
return [{ options }];
}, [settings?.vlcBackgroundColor, t, updateSettings]);
const outlineColorOptionGroups = useMemo(() => {
const colors = Object.keys(VLC_COLORS) as VLCColor[];
const options = colors.map((color) => ({
type: "radio" as const,
label: t(`home.settings.subtitles.colors.${color}`),
value: color,
selected: (settings?.vlcOutlineColor || "Black") === color,
onPress: () => updateSettings({ vlcOutlineColor: color }),
}));
return [{ options }];
}, [settings?.vlcOutlineColor, t, updateSettings]);
const outlineThicknessOptionGroups = useMemo(() => {
const thicknesses = Object.keys(OUTLINE_THICKNESS) as OutlineThickness[];
const options = thicknesses.map((thickness) => ({
type: "radio" as const,
label: t(`home.settings.subtitles.thickness.${thickness}`),
value: thickness,
selected: (settings?.vlcOutlineThickness || "Normal") === thickness,
onPress: () => updateSettings({ vlcOutlineThickness: thickness }),
}));
return [{ options }];
}, [settings?.vlcOutlineThickness, t, updateSettings]);
const backgroundOpacityOptionGroups = useMemo(() => {
const opacities = [0, 32, 64, 96, 128, 160, 192, 224, 255];
const options = opacities.map((opacity) => ({
type: "radio" as const,
label: `${Math.round((opacity / 255) * 100)}%`,
value: opacity,
selected: (settings?.vlcBackgroundOpacity ?? 128) === opacity,
onPress: () => updateSettings({ vlcBackgroundOpacity: opacity }),
}));
return [{ options }];
}, [settings?.vlcBackgroundOpacity, updateSettings]);
const outlineOpacityOptionGroups = useMemo(() => {
const opacities = [0, 32, 64, 96, 128, 160, 192, 224, 255];
const options = opacities.map((opacity) => ({
type: "radio" as const,
label: `${Math.round((opacity / 255) * 100)}%`,
value: opacity,
selected: (settings?.vlcOutlineOpacity ?? 255) === opacity,
onPress: () => updateSettings({ vlcOutlineOpacity: opacity }),
}));
return [{ options }];
}, [settings?.vlcOutlineOpacity, updateSettings]);
if (isTv) return null;
if (!settings) return null;
@@ -244,130 +160,14 @@ export const SubtitleToggles: React.FC<Props> = ({ ...props }) => {
disabled={pluginSettings?.subtitleSize?.locked}
>
<Stepper
value={settings.subtitleSize}
value={settings.subtitleSize / 100}
disabled={pluginSettings?.subtitleSize?.locked}
step={5}
min={0}
max={120}
onUpdate={(subtitleSize) => updateSettings({ subtitleSize })}
/>
</ListItem>
<ListItem title={t("home.settings.subtitles.text_color")}>
<PlatformDropdown
groups={textColorOptionGroups}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>
{t(
`home.settings.subtitles.colors.${settings?.vlcTextColor || "White"}`,
)}
</Text>
<Ionicons
name='chevron-expand-sharp'
size={18}
color='#5A5960'
/>
</View>
step={0.1}
min={0.3}
max={1.5}
onUpdate={(value) =>
updateSettings({ subtitleSize: Math.round(value * 100) })
}
title={t("home.settings.subtitles.text_color")}
/>
</ListItem>
<ListItem title={t("home.settings.subtitles.background_color")}>
<PlatformDropdown
groups={backgroundColorOptionGroups}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>
{t(
`home.settings.subtitles.colors.${settings?.vlcBackgroundColor || "Black"}`,
)}
</Text>
<Ionicons
name='chevron-expand-sharp'
size={18}
color='#5A5960'
/>
</View>
}
title={t("home.settings.subtitles.background_color")}
/>
</ListItem>
<ListItem title={t("home.settings.subtitles.outline_color")}>
<PlatformDropdown
groups={outlineColorOptionGroups}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>
{t(
`home.settings.subtitles.colors.${settings?.vlcOutlineColor || "Black"}`,
)}
</Text>
<Ionicons
name='chevron-expand-sharp'
size={18}
color='#5A5960'
/>
</View>
}
title={t("home.settings.subtitles.outline_color")}
/>
</ListItem>
<ListItem title={t("home.settings.subtitles.outline_thickness")}>
<PlatformDropdown
groups={outlineThicknessOptionGroups}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>
{t(
`home.settings.subtitles.thickness.${settings?.vlcOutlineThickness || "Normal"}`,
)}
</Text>
<Ionicons
name='chevron-expand-sharp'
size={18}
color='#5A5960'
/>
</View>
}
title={t("home.settings.subtitles.outline_thickness")}
/>
</ListItem>
<ListItem title={t("home.settings.subtitles.background_opacity")}>
<PlatformDropdown
groups={backgroundOpacityOptionGroups}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>{`${Math.round(((settings?.vlcBackgroundOpacity ?? 128) / 255) * 100)}%`}</Text>
<Ionicons
name='chevron-expand-sharp'
size={18}
color='#5A5960'
/>
</View>
}
title={t("home.settings.subtitles.background_opacity")}
/>
</ListItem>
<ListItem title={t("home.settings.subtitles.outline_opacity")}>
<PlatformDropdown
groups={outlineOpacityOptionGroups}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>{`${Math.round(((settings?.vlcOutlineOpacity ?? 255) / 255) * 100)}%`}</Text>
<Ionicons
name='chevron-expand-sharp'
size={18}
color='#5A5960'
/>
</View>
}
title={t("home.settings.subtitles.outline_opacity")}
/>
</ListItem>
<ListItem title={t("home.settings.subtitles.bold_text")}>
<Switch
value={settings?.vlcIsBold ?? false}
onValueChange={(value) => updateSettings({ vlcIsBold: value })}
/>
</ListItem>
</ListGroup>

View File

@@ -0,0 +1,93 @@
import { Ionicons } from "@expo/vector-icons";
import type React from "react";
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Platform, Switch, View } from "react-native";
import { setHardwareDecode } from "@/modules/sf-player";
import { useSettings, VideoPlayerIOS } from "@/utils/atoms/settings";
import { Text } from "../common/Text";
import { ListGroup } from "../list/ListGroup";
import { ListItem } from "../list/ListItem";
import { PlatformDropdown } from "../PlatformDropdown";
export const VideoPlayerSettings: React.FC = () => {
const { settings, updateSettings } = useSettings();
const { t } = useTranslation();
const handleHardwareDecodeChange = useCallback(
(value: boolean) => {
updateSettings({ ksHardwareDecode: value });
setHardwareDecode(value);
},
[updateSettings],
);
const videoPlayerOptions = useMemo(
() => [
{
options: [
{
type: "radio" as const,
label: t("home.settings.video_player.ksplayer"),
value: VideoPlayerIOS.KSPlayer,
selected: settings?.videoPlayerIOS === VideoPlayerIOS.KSPlayer,
onPress: () =>
updateSettings({ videoPlayerIOS: VideoPlayerIOS.KSPlayer }),
},
{
type: "radio" as const,
label: t("home.settings.video_player.vlc"),
value: VideoPlayerIOS.VLC,
selected: settings?.videoPlayerIOS === VideoPlayerIOS.VLC,
onPress: () =>
updateSettings({ videoPlayerIOS: VideoPlayerIOS.VLC }),
},
],
},
],
[settings?.videoPlayerIOS, t, updateSettings],
);
const getPlayerLabel = useCallback(() => {
switch (settings?.videoPlayerIOS) {
case VideoPlayerIOS.VLC:
return t("home.settings.video_player.vlc");
default:
return t("home.settings.video_player.ksplayer");
}
}, [settings?.videoPlayerIOS, t]);
if (Platform.OS !== "ios" || !settings) return null;
return (
<ListGroup title={t("home.settings.video_player.title")} className='mt-4'>
<ListItem
title={t("home.settings.video_player.video_player")}
subtitle={t("home.settings.video_player.video_player_description")}
>
<PlatformDropdown
groups={videoPlayerOptions}
trigger={
<View className='flex flex-row items-center justify-between py-1.5 pl-3'>
<Text className='mr-1 text-[#8E8D91]'>{getPlayerLabel()}</Text>
<Ionicons name='chevron-expand-sharp' size={18} color='#5A5960' />
</View>
}
title={t("home.settings.video_player.video_player")}
/>
</ListItem>
{settings.videoPlayerIOS === VideoPlayerIOS.KSPlayer && (
<ListItem
title={t("home.settings.subtitles.hardware_decode")}
subtitle={t("home.settings.subtitles.hardware_decode_description")}
>
<Switch
value={settings.ksHardwareDecode}
onValueChange={handleHardwareDecodeChange}
/>
</ListItem>
)}
</ListGroup>
);
};

View File

@@ -18,7 +18,6 @@ interface BottomControlsProps {
showRemoteBubble: boolean;
currentTime: number;
remainingTime: number;
isVlc: boolean;
showSkipButton: boolean;
showSkipCreditButton: boolean;
hasContentAfterCredits: boolean;
@@ -67,7 +66,6 @@ export const BottomControls: FC<BottomControlsProps> = ({
showRemoteBubble,
currentTime,
remainingTime,
isVlc,
showSkipButton,
showSkipCreditButton,
hasContentAfterCredits,
@@ -157,7 +155,7 @@ export const BottomControls: FC<BottomControlsProps> = ({
? false
: // Show during credits if no content after, OR near end of video
(showSkipCreditButton && !hasContentAfterCredits) ||
(isVlc ? remainingTime < 10000 : remainingTime < 10)
remainingTime < 10000
}
onFinish={handleNextEpisodeAutoPlay}
onPress={handleNextEpisodeManual}
@@ -215,7 +213,6 @@ export const BottomControls: FC<BottomControlsProps> = ({
<TimeDisplay
currentTime={currentTime}
remainingTime={remainingTime}
isVlc={isVlc}
/>
</View>
</View>

View File

@@ -4,16 +4,8 @@ import type {
MediaSourceInfo,
} from "@jellyfin/sdk/lib/generated-client";
import { useLocalSearchParams, useRouter } from "expo-router";
import {
type Dispatch,
type FC,
type MutableRefObject,
type SetStateAction,
useCallback,
useEffect,
useState,
} from "react";
import { useWindowDimensions } from "react-native";
import { type FC, useCallback, useEffect, useState } from "react";
import { StyleSheet, useWindowDimensions, View } from "react-native";
import Animated, {
Easing,
type SharedValue,
@@ -28,7 +20,6 @@ import { useHaptic } from "@/hooks/useHaptic";
import { useIntroSkipper } from "@/hooks/useIntroSkipper";
import { usePlaybackManager } from "@/hooks/usePlaybackManager";
import { useTrickplay } from "@/hooks/useTrickplay";
import type { TrackInfo, VlcPlayerViewRef } from "@/modules/VlcPlayer.types";
import { DownloadedItem } from "@/providers/Downloads/types";
import { useSettings } from "@/utils/atoms/settings";
import { getDefaultPlaySettings } from "@/utils/jellyfin/getDefaultPlaySettings";
@@ -36,7 +27,6 @@ import { ticksToMs } from "@/utils/time";
import { BottomControls } from "./BottomControls";
import { CenterControls } from "./CenterControls";
import { CONTROLS_CONSTANTS } from "./constants";
import { ControlProvider } from "./contexts/ControlContext";
import { EpisodeList } from "./EpisodeList";
import { GestureOverlay } from "./GestureOverlay";
import { HeaderControls } from "./HeaderControls";
@@ -44,42 +34,30 @@ import { useRemoteControl } from "./hooks/useRemoteControl";
import { useVideoNavigation } from "./hooks/useVideoNavigation";
import { useVideoSlider } from "./hooks/useVideoSlider";
import { useVideoTime } from "./hooks/useVideoTime";
import { type ScaleFactor } from "./ScaleFactorSelector";
import { useControlsTimeout } from "./useControlsTimeout";
import { type AspectRatio } from "./VideoScalingModeSelector";
interface Props {
item: BaseItemDto;
videoRef: MutableRefObject<VlcPlayerViewRef | null>;
isPlaying: boolean;
isSeeking: SharedValue<boolean>;
cacheProgress: SharedValue<number>;
progress: SharedValue<number>;
isBuffering: boolean;
showControls: boolean;
enableTrickplay?: boolean;
togglePlay: () => void;
setShowControls: (shown: boolean) => void;
offline?: boolean;
isVideoLoaded?: boolean;
mediaSource?: MediaSourceInfo | null;
seek: (ticks: number) => void;
startPictureInPicture?: () => Promise<void>;
play: () => void;
pause: () => void;
getAudioTracks?: (() => Promise<TrackInfo[] | null>) | (() => TrackInfo[]);
getSubtitleTracks?: (() => Promise<TrackInfo[] | null>) | (() => TrackInfo[]);
setSubtitleURL?: (url: string, customName: string) => void;
setSubtitleTrack?: (index: number) => void;
setAudioTrack?: (index: number) => void;
setVideoAspectRatio?: (aspectRatio: string | null) => Promise<void>;
setVideoScaleFactor?: (scaleFactor: number) => Promise<void>;
aspectRatio?: AspectRatio;
scaleFactor?: ScaleFactor;
setAspectRatio?: Dispatch<SetStateAction<AspectRatio>>;
setScaleFactor?: Dispatch<SetStateAction<ScaleFactor>>;
isVlc?: boolean;
isZoomedToFill?: boolean;
onZoomToggle?: () => void;
api?: Api | null;
downloadedFiles?: DownloadedItem[];
}
@@ -99,20 +77,11 @@ export const Controls: FC<Props> = ({
showControls,
setShowControls,
mediaSource,
isVideoLoaded,
getAudioTracks,
getSubtitleTracks,
setSubtitleURL,
setSubtitleTrack,
setAudioTrack,
setVideoAspectRatio,
setVideoScaleFactor,
aspectRatio = "default",
scaleFactor = 1.0,
setAspectRatio,
setScaleFactor,
isZoomedToFill = false,
onZoomToggle,
offline = false,
isVlc = false,
api = null,
downloadedFiles = undefined,
}) => {
@@ -194,17 +163,13 @@ export const Controls: FC<Props> = ({
zIndex: 10,
}));
// Initialize progress values
// Initialize progress values - MPV uses milliseconds
useEffect(() => {
if (item) {
progress.value = isVlc
? ticksToMs(item?.UserData?.PlaybackPositionTicks)
: item?.UserData?.PlaybackPositionTicks || 0;
max.value = isVlc
? ticksToMs(item.RunTimeTicks || 0)
: item.RunTimeTicks || 0;
progress.value = ticksToMs(item?.UserData?.PlaybackPositionTicks);
max.value = ticksToMs(item.RunTimeTicks || 0);
}
}, [item, isVlc, progress, max]);
}, [item, progress, max]);
// Navigation hooks
const {
@@ -215,7 +180,6 @@ export const Controls: FC<Props> = ({
} = useVideoNavigation({
progress,
isPlaying,
isVlc,
seek,
play,
});
@@ -225,7 +189,6 @@ export const Controls: FC<Props> = ({
progress,
max,
isSeeking,
isVlc,
});
const toggleControls = useCallback(() => {
@@ -248,7 +211,6 @@ export const Controls: FC<Props> = ({
progress,
min,
max,
isVlc,
showControls,
isPlaying,
seek,
@@ -273,7 +235,6 @@ export const Controls: FC<Props> = ({
progress,
isSeeking,
isPlaying,
isVlc,
seek,
play,
pause,
@@ -302,9 +263,8 @@ export const Controls: FC<Props> = ({
: current.actual;
} else {
// When not scrubbing, only update if progress changed significantly (1 second)
const progressUnit = isVlc
? CONTROLS_CONSTANTS.PROGRESS_UNIT_MS
: CONTROLS_CONSTANTS.PROGRESS_UNIT_TICKS;
// MPV uses milliseconds
const progressUnit = CONTROLS_CONSTANTS.PROGRESS_UNIT_MS;
const progressDiff = Math.abs(current.actual - effectiveProgress.value);
if (progressDiff >= progressUnit) {
effectiveProgress.value = current.actual;
@@ -325,7 +285,6 @@ export const Controls: FC<Props> = ({
currentTime,
seek,
play,
isVlc,
offline,
api,
downloadedFiles,
@@ -337,7 +296,6 @@ export const Controls: FC<Props> = ({
currentTime,
seek,
play,
isVlc,
offline,
api,
downloadedFiles,
@@ -361,12 +319,10 @@ export const Controls: FC<Props> = ({
mediaSource: newMediaSource,
audioIndex: defaultAudioIndex,
subtitleIndex: defaultSubtitleIndex,
} = getDefaultPlaySettings(
item,
settings,
previousIndexes,
mediaSource ?? undefined,
);
} = getDefaultPlaySettings(item, settings, {
indexes: previousIndexes,
source: mediaSource ?? undefined,
});
const queryParams = new URLSearchParams({
...(offline && { offline: "true" }),
@@ -379,8 +335,6 @@ export const Controls: FC<Props> = ({
item.UserData?.PlaybackPositionTicks?.toString() ?? "",
}).toString();
console.log("queryParams", queryParams);
router.replace(`player/direct-player?${queryParams}` as any);
},
[settings, subtitleIndex, audioIndex, mediaSource, bitrateValue, router],
@@ -471,6 +425,7 @@ export const Controls: FC<Props> = ({
episodeView,
onHideControls: hideControls,
timeout: CONTROLS_CONSTANTS.TIMEOUT,
disabled: true,
});
const switchOnEpisodeMode = useCallback(() => {
@@ -481,11 +436,7 @@ export const Controls: FC<Props> = ({
}, [isPlaying, togglePlay]);
return (
<ControlProvider
item={item}
mediaSource={mediaSource}
isVideoLoaded={isVideoLoaded}
>
<View style={styles.controlsContainer} pointerEvents='box-none'>
{episodeView ? (
<EpisodeList
item={item}
@@ -517,17 +468,10 @@ export const Controls: FC<Props> = ({
goToNextItem={goToNextItem}
previousItem={previousItem}
nextItem={nextItem}
getAudioTracks={getAudioTracks}
getSubtitleTracks={getSubtitleTracks}
setAudioTrack={setAudioTrack}
setSubtitleTrack={setSubtitleTrack}
setSubtitleURL={setSubtitleURL}
aspectRatio={aspectRatio}
scaleFactor={scaleFactor}
setAspectRatio={setAspectRatio}
setScaleFactor={setScaleFactor}
setVideoAspectRatio={setVideoAspectRatio}
setVideoScaleFactor={setVideoScaleFactor}
isZoomedToFill={isZoomedToFill}
onZoomToggle={onZoomToggle}
/>
</Animated.View>
<Animated.View
@@ -556,7 +500,6 @@ export const Controls: FC<Props> = ({
showRemoteBubble={showRemoteBubble}
currentTime={currentTime}
remainingTime={remainingTime}
isVlc={isVlc}
showSkipButton={showSkipButton}
showSkipCreditButton={showSkipCreditButton}
hasContentAfterCredits={hasContentAfterCredits}
@@ -585,6 +528,16 @@ export const Controls: FC<Props> = ({
{settings.maxAutoPlayEpisodeCount.value !== -1 && (
<ContinueWatchingOverlay goToNextItem={handleContinueWatching} />
)}
</ControlProvider>
</View>
);
};
const styles = StyleSheet.create({
controlsContainer: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
},
});

View File

@@ -4,7 +4,7 @@ import type {
MediaSourceInfo,
} from "@jellyfin/sdk/lib/generated-client";
import { useRouter } from "expo-router";
import { type Dispatch, type FC, type SetStateAction } from "react";
import type { FC } from "react";
import {
Platform,
TouchableOpacity,
@@ -13,15 +13,11 @@ import {
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useHaptic } from "@/hooks/useHaptic";
import { useSettings, VideoPlayer } from "@/utils/atoms/settings";
import { useSettings } from "@/utils/atoms/settings";
import { ICON_SIZES } from "./constants";
import { VideoProvider } from "./contexts/VideoContext";
import DropdownView from "./dropdown/DropdownView";
import { type ScaleFactor, ScaleFactorSelector } from "./ScaleFactorSelector";
import {
type AspectRatio,
AspectRatioSelector,
} from "./VideoScalingModeSelector";
import { type AspectRatio } from "./VideoScalingModeSelector";
import { ZoomToggle } from "./ZoomToggle";
interface HeaderControlsProps {
item: BaseItemDto;
@@ -34,17 +30,10 @@ interface HeaderControlsProps {
goToNextItem: (options: { isAutoPlay?: boolean }) => void;
previousItem?: BaseItemDto | null;
nextItem?: BaseItemDto | null;
getAudioTracks?: (() => Promise<any[] | null>) | (() => any[]);
getSubtitleTracks?: (() => Promise<any[] | null>) | (() => any[]);
setAudioTrack?: (index: number) => void;
setSubtitleTrack?: (index: number) => void;
setSubtitleURL?: (url: string, customName: string) => void;
aspectRatio?: AspectRatio;
scaleFactor?: ScaleFactor;
setAspectRatio?: Dispatch<SetStateAction<AspectRatio>>;
setScaleFactor?: Dispatch<SetStateAction<ScaleFactor>>;
setVideoAspectRatio?: (aspectRatio: string | null) => Promise<void>;
setVideoScaleFactor?: (scaleFactor: number) => Promise<void>;
isZoomedToFill?: boolean;
onZoomToggle?: () => void;
}
export const HeaderControls: FC<HeaderControlsProps> = ({
@@ -58,39 +47,17 @@ export const HeaderControls: FC<HeaderControlsProps> = ({
goToNextItem,
previousItem,
nextItem,
getAudioTracks,
getSubtitleTracks,
setAudioTrack,
setSubtitleTrack,
setSubtitleURL,
aspectRatio = "default",
scaleFactor = 1.0,
setAspectRatio,
setScaleFactor,
setVideoAspectRatio,
setVideoScaleFactor,
aspectRatio: _aspectRatio = "default",
setVideoAspectRatio: _setVideoAspectRatio,
isZoomedToFill = false,
onZoomToggle,
}) => {
const { settings } = useSettings();
const router = useRouter();
const insets = useSafeAreaInsets();
const { width: screenWidth } = useWindowDimensions();
const { width: _screenWidth } = useWindowDimensions();
const lightHapticFeedback = useHaptic("light");
const handleAspectRatioChange = async (newRatio: AspectRatio) => {
if (!setAspectRatio || !setVideoAspectRatio) return;
setAspectRatio(newRatio);
const aspectRatioString = newRatio === "default" ? null : newRatio;
await setVideoAspectRatio(aspectRatioString);
};
const handleScaleFactorChange = async (newScale: ScaleFactor) => {
if (!setScaleFactor || !setVideoScaleFactor) return;
setScaleFactor(newScale);
await setVideoScaleFactor(newScale);
};
const onClose = async () => {
lightHapticFeedback();
router.back();
@@ -102,46 +69,34 @@ export const HeaderControls: FC<HeaderControlsProps> = ({
{
position: "absolute",
top: settings?.safeAreaInControlsEnabled ? insets.top : 0,
left: settings?.safeAreaInControlsEnabled ? insets.left : 0,
right: settings?.safeAreaInControlsEnabled ? insets.right : 0,
width: settings?.safeAreaInControlsEnabled
? screenWidth - insets.left - insets.right
: screenWidth,
},
]}
pointerEvents={showControls ? "auto" : "none"}
className={"flex flex-row w-full pt-2"}
className='flex flex-row justify-between'
>
<View className='mr-auto' pointerEvents='box-none'>
<View className='mr-auto p-2' pointerEvents='box-none'>
{!Platform.isTV && (!offline || !mediaSource?.TranscodingUrl) && (
<VideoProvider
getAudioTracks={getAudioTracks}
getSubtitleTracks={getSubtitleTracks}
setAudioTrack={setAudioTrack}
setSubtitleTrack={setSubtitleTrack}
setSubtitleURL={setSubtitleURL}
>
<View pointerEvents='auto'>
<DropdownView />
</View>
</VideoProvider>
<View pointerEvents='auto'>
<DropdownView />
</View>
)}
</View>
<View className='flex flex-row items-center space-x-2'>
{!Platform.isTV &&
(settings.defaultPlayer === VideoPlayer.VLC_4 ||
Platform.OS === "android") && (
<TouchableOpacity
onPress={startPictureInPicture}
className='aspect-square flex flex-col rounded-xl items-center justify-center p-2'
>
<MaterialIcons
name='picture-in-picture'
size={ICON_SIZES.HEADER}
color='white'
/>
</TouchableOpacity>
)}
{!Platform.isTV && startPictureInPicture && (
<TouchableOpacity
onPress={startPictureInPicture}
className='aspect-square flex flex-col rounded-xl items-center justify-center p-2'
>
<MaterialIcons
name='picture-in-picture'
size={ICON_SIZES.HEADER}
color='white'
/>
</TouchableOpacity>
)}
{item?.Type === "Episode" && (
<TouchableOpacity
onPress={switchOnEpisodeMode}
@@ -174,15 +129,20 @@ export const HeaderControls: FC<HeaderControlsProps> = ({
/>
</TouchableOpacity>
)}
<AspectRatioSelector
{/*<AspectRatioSelector
currentRatio={aspectRatio}
onRatioChange={handleAspectRatioChange}
onRatioChange={async (newRatio) => {
if (setVideoAspectRatio) {
const aspectRatioString = newRatio === "default" ? null : newRatio;
await setVideoAspectRatio(aspectRatioString);
}
}}
disabled={!setVideoAspectRatio}
/>
<ScaleFactorSelector
currentScale={scaleFactor}
onScaleChange={handleScaleFactorChange}
disabled={!setVideoScaleFactor}
/>*/}
<ZoomToggle
isZoomedToFill={isZoomedToFill}
onToggle={onZoomToggle ?? (() => {})}
disabled={!onZoomToggle}
/>
<TouchableOpacity
onPress={onClose}

View File

@@ -1,146 +0,0 @@
import { Ionicons } from "@expo/vector-icons";
import React, { useMemo } from "react";
import { Platform, View } from "react-native";
import {
type OptionGroup,
PlatformDropdown,
} from "@/components/PlatformDropdown";
import { useHaptic } from "@/hooks/useHaptic";
export type ScaleFactor =
| 1.0
| 1.1
| 1.2
| 1.3
| 1.4
| 1.5
| 1.6
| 1.7
| 1.8
| 1.9
| 2.0;
interface ScaleFactorSelectorProps {
currentScale: ScaleFactor;
onScaleChange: (scale: ScaleFactor) => void;
disabled?: boolean;
}
interface ScaleFactorOption {
id: ScaleFactor;
label: string;
description: string;
}
const SCALE_FACTOR_OPTIONS: ScaleFactorOption[] = [
{
id: 1.0,
label: "1.0x",
description: "Original size",
},
{
id: 1.1,
label: "1.1x",
description: "10% larger",
},
{
id: 1.2,
label: "1.2x",
description: "20% larger",
},
{
id: 1.3,
label: "1.3x",
description: "30% larger",
},
{
id: 1.4,
label: "1.4x",
description: "40% larger",
},
{
id: 1.5,
label: "1.5x",
description: "50% larger",
},
{
id: 1.6,
label: "1.6x",
description: "60% larger",
},
{
id: 1.7,
label: "1.7x",
description: "70% larger",
},
{
id: 1.8,
label: "1.8x",
description: "80% larger",
},
{
id: 1.9,
label: "1.9x",
description: "90% larger",
},
{
id: 2.0,
label: "2.0x",
description: "Double size",
},
];
export const ScaleFactorSelector: React.FC<ScaleFactorSelectorProps> = ({
currentScale,
onScaleChange,
disabled = false,
}) => {
const lightHapticFeedback = useHaptic("light");
const handleScaleSelect = (scale: ScaleFactor) => {
onScaleChange(scale);
lightHapticFeedback();
};
const optionGroups = useMemo<OptionGroup[]>(() => {
return [
{
options: SCALE_FACTOR_OPTIONS.map((option) => ({
type: "radio" as const,
label: option.label,
value: option.id,
selected: option.id === currentScale,
onPress: () => handleScaleSelect(option.id),
disabled,
})),
},
];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentScale, disabled]);
const trigger = useMemo(
() => (
<View
className='aspect-square flex flex-col rounded-xl items-center justify-center p-2'
style={{ opacity: disabled ? 0.5 : 1 }}
>
<Ionicons name='search-outline' size={24} color='white' />
</View>
),
[disabled],
);
// Hide on TV platforms
if (Platform.isTV) return null;
return (
<PlatformDropdown
title='Scale Factor'
groups={optionGroups}
trigger={trigger}
bottomSheetConfig={{
enablePanDownToClose: true,
}}
/>
);
};

View File

@@ -6,18 +6,20 @@ import { formatTimeString } from "@/utils/time";
interface TimeDisplayProps {
currentTime: number;
remainingTime: number;
isVlc: boolean;
}
/**
* Displays current time and remaining time.
* MPV player uses milliseconds for time values.
*/
export const TimeDisplay: FC<TimeDisplayProps> = ({
currentTime,
remainingTime,
isVlc,
}) => {
const getFinishTime = () => {
const now = new Date();
const remainingMs = isVlc ? remainingTime : remainingTime * 1000;
const finishTime = new Date(now.getTime() + remainingMs);
// remainingTime is in ms
const finishTime = new Date(now.getTime() + remainingTime);
return finishTime.toLocaleTimeString([], {
hour: "2-digit",
minute: "2-digit",
@@ -28,11 +30,11 @@ export const TimeDisplay: FC<TimeDisplayProps> = ({
return (
<View className='flex flex-row items-center justify-between mt-2'>
<Text className='text-[12px] text-neutral-400'>
{formatTimeString(currentTime, isVlc ? "ms" : "s")}
{formatTimeString(currentTime, "ms")}
</Text>
<View className='flex flex-col items-end'>
<Text className='text-[12px] text-neutral-400'>
-{formatTimeString(remainingTime, isVlc ? "ms" : "s")}
-{formatTimeString(remainingTime, "ms")}
</Text>
<Text className='text-[10px] text-neutral-500 opacity-70'>
ends at {getFinishTime()}

View File

@@ -0,0 +1,44 @@
import { Ionicons } from "@expo/vector-icons";
import React from "react";
import { Platform, TouchableOpacity, View } from "react-native";
import { useHaptic } from "@/hooks/useHaptic";
import { ICON_SIZES } from "./constants";
interface ZoomToggleProps {
isZoomedToFill: boolean;
onToggle: () => void;
disabled?: boolean;
}
export const ZoomToggle: React.FC<ZoomToggleProps> = ({
isZoomedToFill,
onToggle,
disabled = false,
}) => {
const lightHapticFeedback = useHaptic("light");
const handlePress = () => {
if (disabled) return;
lightHapticFeedback();
onToggle();
};
// Hide on TV platforms
if (Platform.isTV) return null;
return (
<TouchableOpacity
onPress={handlePress}
disabled={disabled}
className='aspect-square flex flex-col rounded-xl items-center justify-center p-2'
>
<View style={{ opacity: disabled ? 0.5 : 1 }}>
<Ionicons
name={isZoomedToFill ? "contract-outline" : "expand-outline"}
size={ICON_SIZES.HEADER}
color='white'
/>
</View>
</TouchableOpacity>
);
};

View File

@@ -1,44 +0,0 @@
import type {
BaseItemDto,
MediaSourceInfo,
} from "@jellyfin/sdk/lib/generated-client";
import type React from "react";
import { createContext, type ReactNode, useContext } from "react";
interface ControlContextProps {
item: BaseItemDto;
mediaSource: MediaSourceInfo | null | undefined;
isVideoLoaded: boolean | undefined;
}
const ControlContext = createContext<ControlContextProps | undefined>(
undefined,
);
interface ControlProviderProps {
children: ReactNode;
item: BaseItemDto;
mediaSource: MediaSourceInfo | null | undefined;
isVideoLoaded: boolean | undefined;
}
export const ControlProvider: React.FC<ControlProviderProps> = ({
children,
item,
mediaSource,
isVideoLoaded,
}) => {
return (
<ControlContext.Provider value={{ item, mediaSource, isVideoLoaded }}>
{children}
</ControlContext.Provider>
);
};
export const useControlContext = () => {
const context = useContext(ControlContext);
if (context === undefined) {
throw new Error("useControlContext must be used within a ControlProvider");
}
return context;
};

View File

@@ -0,0 +1,115 @@
import type {
BaseItemDto,
MediaSourceInfo,
} from "@jellyfin/sdk/lib/generated-client";
import React, {
createContext,
type MutableRefObject,
type ReactNode,
useContext,
useMemo,
} from "react";
import type { SfPlayerViewRef, VlcPlayerViewRef } from "@/modules";
// Union type for both player refs
type PlayerRef = SfPlayerViewRef | VlcPlayerViewRef;
interface PlayerContextProps {
playerRef: MutableRefObject<PlayerRef | null>;
item: BaseItemDto;
mediaSource: MediaSourceInfo | null | undefined;
isVideoLoaded: boolean;
tracksReady: boolean;
}
const PlayerContext = createContext<PlayerContextProps | undefined>(undefined);
interface PlayerProviderProps {
children: ReactNode;
playerRef: MutableRefObject<PlayerRef | null>;
item: BaseItemDto;
mediaSource: MediaSourceInfo | null | undefined;
isVideoLoaded: boolean;
tracksReady: boolean;
}
export const PlayerProvider: React.FC<PlayerProviderProps> = ({
children,
playerRef,
item,
mediaSource,
isVideoLoaded,
tracksReady,
}) => {
const value = useMemo(
() => ({ playerRef, item, mediaSource, isVideoLoaded, tracksReady }),
[playerRef, item, mediaSource, isVideoLoaded, tracksReady],
);
return (
<PlayerContext.Provider value={value}>{children}</PlayerContext.Provider>
);
};
// Core context hook
export const usePlayerContext = () => {
const context = useContext(PlayerContext);
if (!context)
throw new Error("usePlayerContext must be used within PlayerProvider");
return context;
};
// Player controls hook - supports both SfPlayer (iOS) and VlcPlayer (Android)
export const usePlayerControls = () => {
const { playerRef } = usePlayerContext();
// Helper to get SfPlayer-specific ref (for iOS-only features)
const getSfRef = () => playerRef.current as SfPlayerViewRef | null;
return {
// Subtitle controls (both players support these, but with different interfaces)
getSubtitleTracks: async () => {
return playerRef.current?.getSubtitleTracks?.() ?? null;
},
setSubtitleTrack: (trackId: number) => {
playerRef.current?.setSubtitleTrack?.(trackId);
},
// iOS only (SfPlayer)
disableSubtitles: () => {
getSfRef()?.disableSubtitles?.();
},
addSubtitleFile: (url: string, select = true) => {
getSfRef()?.addSubtitleFile?.(url, select);
},
// Audio controls (both players)
getAudioTracks: async () => {
return playerRef.current?.getAudioTracks?.() ?? null;
},
setAudioTrack: (trackId: number) => {
playerRef.current?.setAudioTrack?.(trackId);
},
// Playback controls (both players)
play: () => playerRef.current?.play?.(),
pause: () => playerRef.current?.pause?.(),
seekTo: (position: number) => playerRef.current?.seekTo?.(position),
// iOS only (SfPlayer)
seekBy: (offset: number) => getSfRef()?.seekBy?.(offset),
setSpeed: (speed: number) => getSfRef()?.setSpeed?.(speed),
// Subtitle positioning - iOS only (SfPlayer)
setSubtitleScale: (scale: number) => getSfRef()?.setSubtitleScale?.(scale),
setSubtitlePosition: (position: number) =>
getSfRef()?.setSubtitlePosition?.(position),
setSubtitleMarginY: (margin: number) =>
getSfRef()?.setSubtitleMarginY?.(margin),
setSubtitleFontSize: (size: number) =>
getSfRef()?.setSubtitleFontSize?.(size),
// PiP (both players)
startPictureInPicture: () => playerRef.current?.startPictureInPicture?.(),
// iOS only (SfPlayer)
stopPictureInPicture: () => getSfRef()?.stopPictureInPicture?.(),
};
};

View File

@@ -1,3 +1,51 @@
/**
* VideoContext.tsx
*
* Manages subtitle and audio track state for the video player UI.
*
* ============================================================================
* ARCHITECTURE
* ============================================================================
*
* - Jellyfin is source of truth for subtitle list (embedded + external)
* - KSPlayer only knows about:
* - Embedded subs it finds in the video stream
* - External subs we explicitly add via addSubtitleFile()
* - UI shows Jellyfin's complete list
* - On selection: either select embedded track or load external URL
*
* ============================================================================
* INDEX TYPES
* ============================================================================
*
* 1. SERVER INDEX (sub.Index / track.index)
* - Jellyfin's server-side stream index
* - Used to report playback state to Jellyfin server
* - Value of -1 means disabled/none
*
* 2. MPV INDEX (track.mpvIndex)
* - KSPlayer's internal track ID
* - KSPlayer orders tracks as: [all embedded, then all external]
* - IDs: 1..embeddedCount for embedded, embeddedCount+1.. for external
* - Value of -1 means track needs replacePlayer() (e.g., burned-in sub)
*
* ============================================================================
* SUBTITLE HANDLING
* ============================================================================
*
* Embedded (DeliveryMethod.Embed):
* - Already in KSPlayer's track list
* - Select via setSubtitleTrack(mpvId)
*
* External (DeliveryMethod.External):
* - Loaded into KSPlayer's srtControl on video start
* - Select via setSubtitleTrack(embeddedCount + externalPosition + 1)
*
* Image-based during transcoding:
* - Burned into video by Jellyfin, not in KSPlayer
* - Requires replacePlayer() to change
*/
import { SubtitleDeliveryMethod } from "@jellyfin/sdk/lib/generated-client";
import { router, useLocalSearchParams } from "expo-router";
import type React from "react";
@@ -9,52 +57,26 @@ import {
useMemo,
useState,
} from "react";
import type { TrackInfo } from "@/modules/VlcPlayer.types";
import type { SfAudioTrack } from "@/modules";
import { isImageBasedSubtitle } from "@/utils/jellyfin/subtitleUtils";
import type { Track } from "../types";
import { useControlContext } from "./ControlContext";
import { usePlayerContext, usePlayerControls } from "./PlayerContext";
interface VideoContextProps {
audioTracks: Track[] | null;
subtitleTracks: Track[] | null;
setAudioTrack: ((index: number) => void) | undefined;
setSubtitleTrack: ((index: number) => void) | undefined;
setSubtitleURL: ((url: string, customName: string) => void) | undefined;
audioTracks: Track[] | null;
}
const VideoContext = createContext<VideoContextProps | undefined>(undefined);
interface VideoProviderProps {
children: ReactNode;
getAudioTracks:
| (() => Promise<TrackInfo[] | null>)
| (() => TrackInfo[])
| undefined;
getSubtitleTracks:
| (() => Promise<TrackInfo[] | null>)
| (() => TrackInfo[])
| undefined;
setAudioTrack: ((index: number) => void) | undefined;
setSubtitleTrack: ((index: number) => void) | undefined;
setSubtitleURL: ((url: string, customName: string) => void) | undefined;
}
export const VideoProvider: React.FC<VideoProviderProps> = ({
export const VideoProvider: React.FC<{ children: ReactNode }> = ({
children,
getSubtitleTracks,
getAudioTracks,
setSubtitleTrack,
setSubtitleURL,
setAudioTrack,
}) => {
const [audioTracks, setAudioTracks] = useState<Track[] | null>(null);
const [subtitleTracks, setSubtitleTracks] = useState<Track[] | null>(null);
const [audioTracks, setAudioTracks] = useState<Track[] | null>(null);
const ControlContext = useControlContext();
const isVideoLoaded = ControlContext?.isVideoLoaded;
const mediaSource = ControlContext?.mediaSource;
const allSubs =
mediaSource?.MediaStreams?.filter((s) => s.Type === "Subtitle") || [];
const { tracksReady, mediaSource } = usePlayerContext();
const playerControls = usePlayerControls();
const { itemId, audioIndex, bitrateValue, subtitleIndex, playbackPosition } =
useLocalSearchParams<{
@@ -66,185 +88,189 @@ export const VideoProvider: React.FC<VideoProviderProps> = ({
playbackPosition: string;
}>();
const onTextBasedSubtitle = useMemo(() => {
return (
allSubs.find(
(s) =>
s.Index?.toString() === subtitleIndex &&
(s.DeliveryMethod === SubtitleDeliveryMethod.Embed ||
s.DeliveryMethod === SubtitleDeliveryMethod.Hls ||
s.DeliveryMethod === SubtitleDeliveryMethod.External),
) || subtitleIndex === "-1"
const allSubs =
mediaSource?.MediaStreams?.filter((s) => s.Type === "Subtitle") || [];
const allAudio =
mediaSource?.MediaStreams?.filter((s) => s.Type === "Audio") || [];
const isTranscoding = Boolean(mediaSource?.TranscodingUrl);
/**
* Check if the currently selected subtitle is image-based.
* Used to determine if we need to refresh the player when changing subs.
*/
const isCurrentSubImageBased = useMemo(() => {
if (subtitleIndex === "-1") return false;
const currentSub = allSubs.find(
(s) => s.Index?.toString() === subtitleIndex,
);
return currentSub ? isImageBasedSubtitle(currentSub) : false;
}, [allSubs, subtitleIndex]);
const setPlayerParams = ({
chosenAudioIndex = audioIndex,
chosenSubtitleIndex = subtitleIndex,
}: {
chosenAudioIndex?: string;
chosenSubtitleIndex?: string;
/**
* Refresh the player with new parameters.
* This triggers Jellyfin to re-process the stream (e.g., burn in image subs).
*/
const replacePlayer = (params: {
audioIndex?: string;
subtitleIndex?: string;
}) => {
console.log("chosenSubtitleIndex", chosenSubtitleIndex);
const queryParams = new URLSearchParams({
itemId: itemId ?? "",
audioIndex: chosenAudioIndex,
subtitleIndex: chosenSubtitleIndex,
audioIndex: params.audioIndex ?? audioIndex,
subtitleIndex: params.subtitleIndex ?? subtitleIndex,
mediaSourceId: mediaSource?.Id ?? "",
bitrateValue: bitrateValue,
playbackPosition: playbackPosition,
}).toString();
router.replace(`player/direct-player?${queryParams}` as any);
};
const setTrackParams = (
type: "audio" | "subtitle",
index: number,
serverIndex: number,
) => {
const setTrack = type === "audio" ? setAudioTrack : setSubtitleTrack;
const paramKey = type === "audio" ? "audioIndex" : "subtitleIndex";
// If we're transcoding and we're going from a image based subtitle
// to a text based subtitle, we need to change the player params.
const shouldChangePlayerParams =
type === "subtitle" &&
mediaSource?.TranscodingUrl &&
!onTextBasedSubtitle;
console.log("Set player params", index, serverIndex);
if (shouldChangePlayerParams) {
setPlayerParams({
chosenSubtitleIndex: serverIndex.toString(),
});
return;
}
setTrack?.(serverIndex);
router.setParams({
[paramKey]: serverIndex.toString(),
});
};
// Fetch tracks when ready
useEffect(() => {
if (!tracksReady) return;
const fetchTracks = async () => {
if (getSubtitleTracks) {
let subtitleData: TrackInfo[] | null = null;
try {
subtitleData = await getSubtitleTracks();
} catch (error) {
console.log("[VideoContext] Failed to get subtitle tracks:", error);
return;
}
// Only FOR VLC 3, If we're transcoding, we need to reverse the subtitle data, because VLC reverses the HLS subtitles.
if (
mediaSource?.TranscodingUrl &&
subtitleData &&
subtitleData.length > 1
) {
subtitleData = [subtitleData[0], ...subtitleData.slice(1).reverse()];
}
const audioData = await playerControls.getAudioTracks().catch(() => null);
const playerAudio = (audioData as SfAudioTrack[]) ?? [];
let embedSubIndex = 1;
const processedSubs: Track[] = allSubs?.map((sub) => {
/** A boolean value determining if we should increment the embedSubIndex, currently only Embed and Hls subtitles are automatically added into VLC Player */
const shouldIncrement =
sub.DeliveryMethod === SubtitleDeliveryMethod.Embed ||
sub.DeliveryMethod === SubtitleDeliveryMethod.Hls ||
sub.DeliveryMethod === SubtitleDeliveryMethod.External;
/** The index of subtitle inside VLC Player Itself */
const vlcIndex = subtitleData?.at(embedSubIndex)?.index ?? -1;
if (shouldIncrement) embedSubIndex++;
return {
name: sub.DisplayTitle || "Undefined Subtitle",
// Separate embedded vs external subtitles from Jellyfin's list
// KSPlayer orders tracks as: [all embedded, then all external]
const embeddedSubs = allSubs.filter(
(s) => s.DeliveryMethod === SubtitleDeliveryMethod.Embed,
);
const externalSubs = allSubs.filter(
(s) => s.DeliveryMethod === SubtitleDeliveryMethod.External,
);
// Count embedded subs that will be in KSPlayer
// (excludes image-based subs during transcoding as they're burned in)
const embeddedInPlayer = embeddedSubs.filter(
(s) => !isTranscoding || !isImageBasedSubtitle(s),
);
const subs: Track[] = [];
// Process all Jellyfin subtitles
for (const sub of allSubs) {
const isEmbedded = sub.DeliveryMethod === SubtitleDeliveryMethod.Embed;
const isExternal =
sub.DeliveryMethod === SubtitleDeliveryMethod.External;
// For image-based subs during transcoding, need to refresh player
if (isTranscoding && isImageBasedSubtitle(sub)) {
subs.push({
name: sub.DisplayTitle || "Unknown",
index: sub.Index ?? -1,
setTrack: () =>
shouldIncrement
? setTrackParams("subtitle", vlcIndex, sub.Index ?? -1)
: setPlayerParams({
chosenSubtitleIndex: sub.Index?.toString(),
}),
};
});
// Step 3: Restore the original order
const subtitles: Track[] = processedSubs.sort(
(a, b) => a.index - b.index,
);
// Add a "Disable Subtitles" option
subtitles.unshift({
name: "Disable",
index: -1,
setTrack: () =>
!mediaSource?.TranscodingUrl || onTextBasedSubtitle
? setTrackParams("subtitle", -1, -1)
: setPlayerParams({ chosenSubtitleIndex: "-1" }),
});
setSubtitleTracks(subtitles);
}
if (getAudioTracks) {
let audioData: TrackInfo[] | null = null;
try {
audioData = await getAudioTracks();
} catch (error) {
console.log("[VideoContext] Failed to get audio tracks:", error);
return;
}
const allAudio =
mediaSource?.MediaStreams?.filter((s) => s.Type === "Audio") || [];
const audioTracks: Track[] = allAudio?.map((audio, idx) => {
if (!mediaSource?.TranscodingUrl) {
const vlcIndex = audioData?.at(idx + 1)?.index ?? -1;
return {
name: audio.DisplayTitle ?? "Undefined Audio",
index: audio.Index ?? -1,
setTrack: () =>
setTrackParams("audio", vlcIndex, audio.Index ?? -1),
};
}
return {
name: audio.DisplayTitle ?? "Undefined Audio",
index: audio.Index ?? -1,
setTrack: () =>
setPlayerParams({ chosenAudioIndex: audio.Index?.toString() }),
};
});
// Add a "Disable Audio" option if its not transcoding.
if (!mediaSource?.TranscodingUrl) {
audioTracks.unshift({
name: "Disable",
index: -1,
setTrack: () => setTrackParams("audio", -1, -1),
mpvIndex: -1,
setTrack: () => {
replacePlayer({ subtitleIndex: String(sub.Index) });
},
});
continue;
}
setAudioTracks(audioTracks);
// Calculate KSPlayer track ID based on type
// KSPlayer IDs: [1..embeddedCount] for embedded, [embeddedCount+1..] for external
let mpvId = -1;
if (isEmbedded) {
// Find position among embedded subs that are in player
const embeddedPosition = embeddedInPlayer.findIndex(
(s) => s.Index === sub.Index,
);
if (embeddedPosition !== -1) {
mpvId = embeddedPosition + 1; // 1-based ID
}
} else if (isExternal) {
// Find position among external subs, offset by embedded count
const externalPosition = externalSubs.findIndex(
(s) => s.Index === sub.Index,
);
if (externalPosition !== -1) {
mpvId = embeddedInPlayer.length + externalPosition + 1;
}
}
subs.push({
name: sub.DisplayTitle || "Unknown",
index: sub.Index ?? -1,
mpvIndex: mpvId,
setTrack: () => {
// Transcoding + switching to/from image-based sub
if (
isTranscoding &&
(isImageBasedSubtitle(sub) || isCurrentSubImageBased)
) {
replacePlayer({ subtitleIndex: String(sub.Index) });
return;
}
// Direct switch in player
if (mpvId !== -1) {
playerControls.setSubtitleTrack(mpvId);
router.setParams({ subtitleIndex: String(sub.Index) });
return;
}
// Fallback - refresh player
replacePlayer({ subtitleIndex: String(sub.Index) });
},
});
}
// Add "Disable" option at the beginning
subs.unshift({
name: "Disable",
index: -1,
mpvIndex: -1,
setTrack: () => {
if (isTranscoding && isCurrentSubImageBased) {
replacePlayer({ subtitleIndex: "-1" });
} else {
playerControls.setSubtitleTrack(-1);
router.setParams({ subtitleIndex: "-1" });
}
},
});
// Process audio tracks
const audio: Track[] = allAudio.map((a, idx) => {
const playerTrack = playerAudio[idx];
const mpvId = playerTrack?.id ?? idx + 1;
return {
name: a.DisplayTitle || "Unknown",
index: a.Index ?? -1,
mpvIndex: mpvId,
setTrack: () => {
if (isTranscoding) {
replacePlayer({ audioIndex: String(a.Index) });
return;
}
playerControls.setAudioTrack(mpvId);
router.setParams({ audioIndex: String(a.Index) });
},
};
});
setSubtitleTracks(subs.sort((a, b) => a.index - b.index));
setAudioTracks(audio);
};
fetchTracks();
}, [isVideoLoaded, getAudioTracks, getSubtitleTracks]);
}, [tracksReady, mediaSource]);
return (
<VideoContext.Provider
value={{
audioTracks,
subtitleTracks,
setSubtitleTrack,
setSubtitleURL,
setAudioTrack,
}}
>
<VideoContext.Provider value={{ subtitleTracks, audioTracks }}>
{children}
</VideoContext.Provider>
);
};
export const useVideoContext = () => {
const context = useContext(VideoContext);
if (context === undefined) {
throw new Error("useVideoContext must be used within a VideoProvider");
}
return context;
const ctx = useContext(VideoContext);
if (!ctx)
throw new Error("useVideoContext must be used within VideoProvider");
return ctx;
};

View File

@@ -7,17 +7,26 @@ import {
type OptionGroup,
PlatformDropdown,
} from "@/components/PlatformDropdown";
import { useControlContext } from "../contexts/ControlContext";
import { useSettings } from "@/utils/atoms/settings";
import { usePlayerContext } from "../contexts/PlayerContext";
import { useVideoContext } from "../contexts/VideoContext";
// Subtitle size presets (stored as scale * 100, so 1.0 = 100)
const SUBTITLE_SIZE_PRESETS = [
{ label: "0.5", value: 50 },
{ label: "0.6", value: 60 },
{ label: "0.7", value: 70 },
{ label: "0.8", value: 80 },
{ label: "0.9", value: 90 },
{ label: "1.0", value: 100 },
{ label: "1.1", value: 110 },
{ label: "1.2", value: 120 },
] as const;
const DropdownView = () => {
const videoContext = useVideoContext();
const { subtitleTracks, audioTracks } = videoContext;
const ControlContext = useControlContext();
const [item, mediaSource] = [
ControlContext?.item,
ControlContext?.mediaSource,
];
const { subtitleTracks, audioTracks } = useVideoContext();
const { item, mediaSource } = usePlayerContext();
const { settings, updateSettings } = useSettings();
const router = useRouter();
const { subtitleIndex, audioIndex, bitrateValue, playbackPosition, offline } =
@@ -100,6 +109,18 @@ const DropdownView = () => {
onPress: () => sub.setTrack(),
})),
});
// Subtitle Size Section
groups.push({
title: "Subtitle Size",
options: SUBTITLE_SIZE_PRESETS.map((preset) => ({
type: "radio" as const,
label: preset.label,
value: preset.value.toString(),
selected: settings.subtitleSize === preset.value,
onPress: () => updateSettings({ subtitleSize: preset.value }),
})),
});
}
// Audio Section
@@ -126,6 +147,8 @@ const DropdownView = () => {
audioTracksKey,
subtitleIndex,
audioIndex,
settings.subtitleSize,
updateSettings,
// Note: subtitleTracks and audioTracks are intentionally excluded
// because we use subtitleTracksKey and audioTracksKey for stability
]);
@@ -148,6 +171,7 @@ const DropdownView = () => {
title='Playback Options'
groups={optionGroups}
trigger={trigger}
expoUIConfig={{}}
bottomSheetConfig={{
enablePanDownToClose: true,
}}

View File

@@ -22,7 +22,6 @@ interface UseRemoteControlProps {
progress: SharedValue<number>;
min: SharedValue<number>;
max: SharedValue<number>;
isVlc: boolean;
showControls: boolean;
isPlaying: boolean;
seek: (value: number) => void;
@@ -34,11 +33,14 @@ interface UseRemoteControlProps {
handleSeekBackward: (seconds: number) => void;
}
/**
* Hook to manage TV remote control interactions.
* MPV player uses milliseconds for time values.
*/
export function useRemoteControl({
progress,
min,
max,
isVlc,
showControls,
isPlaying,
seek,
@@ -61,21 +63,18 @@ export function useRemoteControl({
const longPressTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(
null,
);
const SCRUB_INTERVAL = isVlc
? CONTROLS_CONSTANTS.SCRUB_INTERVAL_MS
: CONTROLS_CONSTANTS.SCRUB_INTERVAL_TICKS;
// MPV uses ms
const SCRUB_INTERVAL = CONTROLS_CONSTANTS.SCRUB_INTERVAL_MS;
const updateTime = useCallback(
(progressValue: number) => {
const progressInTicks = isVlc ? msToTicks(progressValue) : progressValue;
const progressInSeconds = Math.floor(ticksToSeconds(progressInTicks));
const hours = Math.floor(progressInSeconds / 3600);
const minutes = Math.floor((progressInSeconds % 3600) / 60);
const seconds = progressInSeconds % 60;
setTime({ hours, minutes, seconds });
},
[isVlc],
);
const updateTime = useCallback((progressValue: number) => {
// Convert ms to ticks for calculation
const progressInTicks = msToTicks(progressValue);
const progressInSeconds = Math.floor(ticksToSeconds(progressInTicks));
const hours = Math.floor(progressInSeconds / 3600);
const minutes = Math.floor((progressInSeconds % 3600) / 60);
const seconds = progressInSeconds % 60;
setTime({ hours, minutes, seconds });
}, []);
// TV remote control handling (no-op on non-TV platforms)
useTVEventHandler((evt) => {
@@ -102,7 +101,8 @@ export function useRemoteControl({
Math.min(max.value, base + direction * SCRUB_INTERVAL),
);
remoteScrubProgress.value = updated;
const progressInTicks = isVlc ? msToTicks(updated) : updated;
// Convert ms to ticks for trickplay
const progressInTicks = msToTicks(updated);
calculateTrickplayUrl(progressInTicks);
updateTime(updated);
break;
@@ -111,9 +111,8 @@ export function useRemoteControl({
if (isRemoteScrubbing.value && remoteScrubProgress.value != null) {
progress.value = remoteScrubProgress.value;
const seekTarget = isVlc
? Math.max(0, remoteScrubProgress.value)
: Math.max(0, ticksToSeconds(remoteScrubProgress.value));
// MPV uses ms, seek expects ms
const seekTarget = Math.max(0, remoteScrubProgress.value);
seek(seekTarget);
if (isPlaying) play();

View File

@@ -3,20 +3,22 @@ import type { SharedValue } from "react-native-reanimated";
import { useHaptic } from "@/hooks/useHaptic";
import { useSettings } from "@/utils/atoms/settings";
import { writeToLog } from "@/utils/log";
import { secondsToMs, ticksToSeconds } from "@/utils/time";
import { secondsToMs } from "@/utils/time";
interface UseVideoNavigationProps {
progress: SharedValue<number>;
isPlaying: boolean;
isVlc: boolean;
seek: (value: number) => void;
play: () => void;
}
/**
* Hook to manage video navigation (seeking forward/backward).
* MPV player uses milliseconds for time values.
*/
export function useVideoNavigation({
progress,
isPlaying,
isVlc,
seek,
play,
}: UseVideoNavigationProps) {
@@ -30,16 +32,15 @@ export function useVideoNavigation({
try {
const curr = progress.value;
if (curr !== undefined) {
const newTime = isVlc
? Math.max(0, curr - secondsToMs(seconds))
: Math.max(0, ticksToSeconds(curr) - seconds);
// MPV uses ms
const newTime = Math.max(0, curr - secondsToMs(seconds));
seek(newTime);
}
} catch (error) {
writeToLog("ERROR", "Error seeking video backwards", error);
}
},
[isPlaying, isVlc, seek, progress],
[isPlaying, seek, progress],
);
const handleSeekForward = useCallback(
@@ -48,16 +49,15 @@ export function useVideoNavigation({
try {
const curr = progress.value;
if (curr !== undefined) {
const newTime = isVlc
? curr + secondsToMs(seconds)
: ticksToSeconds(curr) + seconds;
// MPV uses ms
const newTime = curr + secondsToMs(seconds);
seek(Math.max(0, newTime));
}
} catch (error) {
writeToLog("ERROR", "Error seeking video forwards", error);
}
},
[isPlaying, isVlc, seek, progress],
[isPlaying, seek, progress],
);
const handleSkipBackward = useCallback(async () => {
@@ -69,9 +69,11 @@ export function useVideoNavigation({
try {
const curr = progress.value;
if (curr !== undefined) {
const newTime = isVlc
? Math.max(0, curr - secondsToMs(settings.rewindSkipTime))
: Math.max(0, ticksToSeconds(curr) - settings.rewindSkipTime);
// MPV uses ms
const newTime = Math.max(
0,
curr - secondsToMs(settings.rewindSkipTime),
);
seek(newTime);
if (wasPlayingRef.current) {
play();
@@ -80,7 +82,7 @@ export function useVideoNavigation({
} catch (error) {
writeToLog("ERROR", "Error seeking video backwards", error);
}
}, [settings, isPlaying, isVlc, play, seek, progress, lightHapticFeedback]);
}, [settings, isPlaying, play, seek, progress, lightHapticFeedback]);
const handleSkipForward = useCallback(async () => {
if (!settings?.forwardSkipTime) {
@@ -91,9 +93,8 @@ export function useVideoNavigation({
try {
const curr = progress.value;
if (curr !== undefined) {
const newTime = isVlc
? curr + secondsToMs(settings.forwardSkipTime)
: ticksToSeconds(curr) + settings.forwardSkipTime;
// MPV uses ms
const newTime = curr + secondsToMs(settings.forwardSkipTime);
seek(Math.max(0, newTime));
if (wasPlayingRef.current) {
play();
@@ -102,7 +103,7 @@ export function useVideoNavigation({
} catch (error) {
writeToLog("ERROR", "Error seeking video forwards", error);
}
}, [settings, isPlaying, isVlc, play, seek, progress, lightHapticFeedback]);
}, [settings, isPlaying, play, seek, progress, lightHapticFeedback]);
return {
handleSeekBackward,

View File

@@ -8,7 +8,6 @@ interface UseVideoSliderProps {
progress: SharedValue<number>;
isSeeking: SharedValue<boolean>;
isPlaying: boolean;
isVlc: boolean;
seek: (value: number) => void;
play: () => void;
pause: () => void;
@@ -16,11 +15,14 @@ interface UseVideoSliderProps {
showControls: boolean;
}
/**
* Hook to manage video slider interactions.
* MPV player uses milliseconds for time values.
*/
export function useVideoSlider({
progress,
isSeeking,
isPlaying,
isVlc,
seek,
play,
pause,
@@ -62,21 +64,20 @@ export function useVideoSlider({
setIsSliding(false);
isSeeking.value = false;
progress.value = value;
const seekValue = Math.max(
0,
Math.floor(isVlc ? value : ticksToSeconds(value)),
);
// MPV uses ms, seek expects ms
const seekValue = Math.max(0, Math.floor(value));
seek(seekValue);
if (wasPlayingRef.current) {
play();
}
},
[isVlc, seek, play, progress, isSeeking],
[seek, play, progress, isSeeking],
);
const handleSliderChange = useCallback(
debounce((value: number) => {
const progressInTicks = isVlc ? msToTicks(value) : value;
// Convert ms to ticks for trickplay
const progressInTicks = msToTicks(value);
calculateTrickplayUrl(progressInTicks);
const progressInSeconds = Math.floor(ticksToSeconds(progressInTicks));
const hours = Math.floor(progressInSeconds / 3600);
@@ -84,7 +85,7 @@ export function useVideoSlider({
const seconds = progressInSeconds % 60;
setTime({ hours, minutes, seconds });
}, CONTROLS_CONSTANTS.SLIDER_DEBOUNCE_MS),
[isVlc, calculateTrickplayUrl],
[calculateTrickplayUrl],
);
return {

View File

@@ -4,21 +4,18 @@ import {
type SharedValue,
useAnimatedReaction,
} from "react-native-reanimated";
import { ticksToSeconds } from "@/utils/time";
interface UseVideoTimeProps {
progress: SharedValue<number>;
max: SharedValue<number>;
isSeeking: SharedValue<boolean>;
isVlc: boolean;
}
export function useVideoTime({
progress,
max,
isSeeking,
isVlc,
}: UseVideoTimeProps) {
/**
* Hook to manage video time display.
* MPV player uses milliseconds for time values.
*/
export function useVideoTime({ progress, max, isSeeking }: UseVideoTimeProps) {
const [currentTime, setCurrentTime] = useState(0);
const [remainingTime, setRemainingTime] = useState(Number.POSITIVE_INFINITY);
@@ -27,19 +24,16 @@ export function useVideoTime({
const updateTimes = useCallback(
(currentProgress: number, maxValue: number) => {
const current = isVlc ? currentProgress : ticksToSeconds(currentProgress);
const remaining = isVlc
? maxValue - currentProgress
: ticksToSeconds(maxValue - currentProgress);
// MPV uses milliseconds
const current = currentProgress;
const remaining = maxValue - currentProgress;
// Only update state if the displayed time actually changed (avoid sub-second updates)
const currentSeconds = Math.floor(current / (isVlc ? 1000 : 1));
const remainingSeconds = Math.floor(remaining / (isVlc ? 1000 : 1));
const lastCurrentSeconds = Math.floor(
lastCurrentTimeRef.current / (isVlc ? 1000 : 1),
);
const currentSeconds = Math.floor(current / 1000);
const remainingSeconds = Math.floor(remaining / 1000);
const lastCurrentSeconds = Math.floor(lastCurrentTimeRef.current / 1000);
const lastRemainingSeconds = Math.floor(
lastRemainingTimeRef.current / (isVlc ? 1000 : 1),
lastRemainingTimeRef.current / 1000,
);
if (
@@ -52,7 +46,7 @@ export function useVideoTime({
lastRemainingTimeRef.current = remaining;
}
},
[isVlc],
[],
);
useAnimatedReaction(

View File

@@ -20,6 +20,7 @@ type TranscodedSubtitle = {
type Track = {
name: string;
index: number;
mpvIndex?: number;
setTrack: () => void;
};

View File

@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { useCallback, useEffect, useRef } from "react";
interface UseControlsTimeoutProps {
showControls: boolean;
@@ -6,6 +6,7 @@ interface UseControlsTimeoutProps {
episodeView: boolean;
onHideControls: () => void;
timeout?: number;
disabled?: boolean;
}
export const useControlsTimeout = ({
@@ -14,6 +15,7 @@ export const useControlsTimeout = ({
episodeView,
onHideControls,
timeout = 10000,
disabled = false,
}: UseControlsTimeoutProps) => {
const controlsTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -23,7 +25,7 @@ export const useControlsTimeout = ({
clearTimeout(controlsTimeoutRef.current);
}
if (showControls && !isSliding && !episodeView) {
if (!disabled && showControls && !isSliding && !episodeView) {
controlsTimeoutRef.current = setTimeout(() => {
onHideControls();
}, timeout);
@@ -37,18 +39,18 @@ export const useControlsTimeout = ({
clearTimeout(controlsTimeoutRef.current);
}
};
}, [showControls, isSliding, episodeView, timeout, onHideControls]);
}, [showControls, isSliding, episodeView, timeout, onHideControls, disabled]);
const handleControlsInteraction = () => {
if (showControls) {
if (controlsTimeoutRef.current) {
clearTimeout(controlsTimeoutRef.current);
}
controlsTimeoutRef.current = setTimeout(() => {
onHideControls();
}, timeout);
const handleControlsInteraction = useCallback(() => {
if (disabled || !showControls) return;
if (controlsTimeoutRef.current) {
clearTimeout(controlsTimeoutRef.current);
}
};
controlsTimeoutRef.current = setTimeout(() => {
onHideControls();
}, timeout);
}, [disabled, showControls, onHideControls, timeout]);
return {
handleControlsInteraction,

View File

@@ -1,94 +0,0 @@
import type React from "react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { TouchableOpacity, View, type ViewProps } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { TrackInfo, VlcPlayerViewRef } from "@/modules/VlcPlayer.types";
import { Text } from "../common/Text";
interface Props extends ViewProps {
playerRef: React.RefObject<VlcPlayerViewRef>;
}
export const VideoDebugInfo: React.FC<Props> = ({ playerRef, ...props }) => {
const [audioTracks, setAudioTracks] = useState<TrackInfo[] | null>(null);
const [subtitleTracks, setSubtitleTracks] = useState<TrackInfo[] | null>(
null,
);
useEffect(() => {
const fetchTracks = async () => {
if (playerRef.current) {
try {
const audio = await playerRef.current.getAudioTracks();
const subtitles = await playerRef.current.getSubtitleTracks();
setAudioTracks(audio);
setSubtitleTracks(subtitles);
} catch (error) {
console.log("[VideoDebugInfo] Failed to fetch tracks:", error);
}
}
};
fetchTracks();
}, [playerRef]);
const insets = useSafeAreaInsets();
const { t } = useTranslation();
return (
<View
style={{
position: "absolute",
top: insets.top,
left: insets.left + 8,
zIndex: 100,
}}
{...props}
>
<Text className='font-bold'>{t("player.playback_state")}</Text>
<Text className='font-bold mt-2.5'>{t("player.audio_tracks")}</Text>
{audioTracks?.map((track, index) => (
<Text key={index}>
{track.name} ({t("player.index")} {track.index})
</Text>
))}
<Text className='font-bold mt-2.5'>{t("player.subtitles_tracks")}</Text>
{subtitleTracks?.map((track, index) => (
<Text key={index}>
{track.name} ({t("player.index")} {track.index})
</Text>
))}
<TouchableOpacity
className='mt-2.5 bg-blue-500 p-2 rounded'
onPress={() => {
if (playerRef.current) {
playerRef.current
.getAudioTracks()
.then(setAudioTracks)
.catch((err) => {
console.log(
"[VideoDebugInfo] Failed to get audio tracks:",
err,
);
});
playerRef.current
.getSubtitleTracks()
.then(setSubtitleTracks)
.catch((err) => {
console.log(
"[VideoDebugInfo] Failed to get subtitle tracks:",
err,
);
});
}
}}
>
<Text className='text-white text-center'>
{t("player.refresh_tracks")}
</Text>
</TouchableOpacity>
</View>
);
};

View File

@@ -0,0 +1,318 @@
import { Ionicons } from "@expo/vector-icons";
import {
BottomSheetBackdrop,
type BottomSheetBackdropProps,
BottomSheetModal,
BottomSheetView,
} from "@gorhom/bottom-sheet";
import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
import { useRouter } from "expo-router";
import React, {
forwardRef,
useCallback,
useImperativeHandle,
useMemo,
useRef,
} from "react";
import { useTranslation } from "react-i18next";
import {
ActivityIndicator,
StyleSheet,
TouchableOpacity,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Text } from "@/components/common/Text";
import {
useAddToWatchlist,
useRemoveFromWatchlist,
} from "@/hooks/useWatchlistMutations";
import {
useItemInWatchlists,
useMyWatchlistsQuery,
} from "@/hooks/useWatchlists";
import type { StreamystatsWatchlist } from "@/utils/streamystats/types";
export interface WatchlistSheetRef {
open: (item: BaseItemDto) => void;
close: () => void;
}
interface WatchlistRowProps {
watchlist: StreamystatsWatchlist;
isInWatchlist: boolean;
isCompatible: boolean;
onToggle: () => void;
isLoading: boolean;
}
const WatchlistRow: React.FC<WatchlistRowProps> = ({
watchlist,
isInWatchlist,
isCompatible,
onToggle,
isLoading,
}) => {
const disabled = !isCompatible && !isInWatchlist;
return (
<TouchableOpacity
onPress={onToggle}
disabled={disabled || isLoading}
className={`bg-neutral-800 px-4 py-3 flex-row items-center justify-between ${disabled ? "opacity-40" : ""}`}
activeOpacity={0.7}
>
<View className='flex-1 mr-4'>
<View className='flex-row items-center gap-2'>
<Text className='text-base font-medium flex-shrink' numberOfLines={1}>
{watchlist.name}
</Text>
{watchlist.allowedItemType && (
<View className='bg-neutral-700 px-1.5 py-0.5 rounded'>
<Text className='text-xs text-neutral-400'>
{watchlist.allowedItemType}
</Text>
</View>
)}
</View>
{watchlist.description && (
<Text className='text-sm text-neutral-400 mt-0.5' numberOfLines={1}>
{watchlist.description}
</Text>
)}
<Text className='text-xs text-neutral-500 mt-1'>
{watchlist.itemCount ?? 0} items
</Text>
</View>
<View className='w-8 h-8 items-center justify-center'>
{isLoading ? (
<ActivityIndicator size='small' color='#a78bfa' />
) : isInWatchlist ? (
<Ionicons name='checkmark-circle' size={26} color='#a78bfa' />
) : isCompatible ? (
<Ionicons name='add-circle-outline' size={26} color='#9ca3af' />
) : (
<Ionicons name='ban-outline' size={22} color='#525252' />
)}
</View>
</TouchableOpacity>
);
};
interface WatchlistSheetContentProps {
item: BaseItemDto;
onClose: () => void;
}
const WatchlistSheetContent: React.FC<WatchlistSheetContentProps> = ({
item,
onClose,
}) => {
const { t } = useTranslation();
const router = useRouter();
const insets = useSafeAreaInsets();
const { data: myWatchlists, isLoading: watchlistsLoading } =
useMyWatchlistsQuery();
const { data: watchlistsContainingItem, isLoading: checkingLoading } =
useItemInWatchlists(item.Id);
const addToWatchlist = useAddToWatchlist();
const removeFromWatchlist = useRemoveFromWatchlist();
const isLoading = watchlistsLoading || checkingLoading;
// Sort watchlists: ones containing item first, then compatible ones, then incompatible
const sortedWatchlists = useMemo(() => {
if (!myWatchlists) return [];
return [...myWatchlists].sort((a, b) => {
const aInWatchlist = watchlistsContainingItem?.includes(a.id) ?? false;
const bInWatchlist = watchlistsContainingItem?.includes(b.id) ?? false;
const aCompatible = !a.allowedItemType || a.allowedItemType === item.Type;
const bCompatible = !b.allowedItemType || b.allowedItemType === item.Type;
// Items in watchlist first
if (aInWatchlist && !bInWatchlist) return -1;
if (!aInWatchlist && bInWatchlist) return 1;
// Then compatible items
if (aCompatible && !bCompatible) return -1;
if (!aCompatible && bCompatible) return 1;
// Then alphabetically
return a.name.localeCompare(b.name);
});
}, [myWatchlists, watchlistsContainingItem, item.Type]);
const handleToggle = useCallback(
async (watchlist: StreamystatsWatchlist) => {
if (!item.Id) return;
const isInWatchlist = watchlistsContainingItem?.includes(watchlist.id);
if (isInWatchlist) {
await removeFromWatchlist.mutateAsync({
watchlistId: watchlist.id,
itemId: item.Id,
watchlistName: watchlist.name,
});
} else {
await addToWatchlist.mutateAsync({
watchlistId: watchlist.id,
itemId: item.Id,
watchlistName: watchlist.name,
});
}
},
[item.Id, watchlistsContainingItem, addToWatchlist, removeFromWatchlist],
);
const handleCreateNew = useCallback(() => {
onClose();
router.push("/(auth)/(tabs)/(watchlists)/create");
}, [onClose, router]);
const isItemCompatible = useCallback(
(watchlist: StreamystatsWatchlist) => {
if (!watchlist.allowedItemType) return true;
return watchlist.allowedItemType === item.Type;
},
[item.Type],
);
if (isLoading) {
return (
<View className='py-12 items-center justify-center'>
<ActivityIndicator size='large' color='#a78bfa' />
<Text className='text-neutral-400 mt-4'>{t("watchlists.loading")}</Text>
</View>
);
}
return (
<View
className='flex-1'
style={{
paddingLeft: Math.max(16, insets.left),
paddingRight: Math.max(16, insets.right),
}}
>
{/* Header */}
<View className='mb-4'>
<Text className='font-bold text-2xl'>
{t("watchlists.select_watchlist")}
</Text>
<Text className='text-neutral-400 mt-1' numberOfLines={1}>
{item.Name}
</Text>
</View>
{/* Watchlist List */}
{sortedWatchlists.length === 0 ? (
<View className='py-8 items-center'>
<Ionicons name='list-outline' size={48} color='#4b5563' />
<Text className='text-neutral-400 text-center mt-4'>
{t("watchlists.empty_title")}
</Text>
<Text className='text-neutral-500 text-center text-sm mt-1'>
{t("watchlists.empty_description")}
</Text>
</View>
) : (
<View className='rounded-xl overflow-hidden mb-4'>
{sortedWatchlists.map((watchlist, index) => (
<React.Fragment key={watchlist.id}>
<WatchlistRow
watchlist={watchlist}
isInWatchlist={
watchlistsContainingItem?.includes(watchlist.id) ?? false
}
isCompatible={isItemCompatible(watchlist)}
onToggle={() => handleToggle(watchlist)}
isLoading={
addToWatchlist.isPending || removeFromWatchlist.isPending
}
/>
{index < sortedWatchlists.length - 1 && (
<View
style={{ height: StyleSheet.hairlineWidth }}
className='bg-neutral-700'
/>
)}
</React.Fragment>
))}
</View>
)}
{/* Create New Button */}
<TouchableOpacity
onPress={handleCreateNew}
className='flex-row items-center justify-center py-4 bg-neutral-800 rounded-xl'
activeOpacity={0.7}
>
<Ionicons name='add' size={20} color='#a78bfa' />
<Text className='text-purple-400 font-medium'>
{t("watchlists.create_new")}
</Text>
</TouchableOpacity>
</View>
);
};
export const WatchlistSheet = forwardRef<WatchlistSheetRef, object>(
(_props, ref) => {
const bottomSheetModalRef = useRef<BottomSheetModal>(null);
const [currentItem, setCurrentItem] = React.useState<BaseItemDto | null>(
null,
);
const insets = useSafeAreaInsets();
useImperativeHandle(ref, () => ({
open: (item: BaseItemDto) => {
setCurrentItem(item);
bottomSheetModalRef.current?.present();
},
close: () => {
bottomSheetModalRef.current?.dismiss();
},
}));
const handleClose = useCallback(() => {
bottomSheetModalRef.current?.dismiss();
}, []);
const renderBackdrop = useCallback(
(props: BottomSheetBackdropProps) => (
<BottomSheetBackdrop
{...props}
disappearsOnIndex={-1}
appearsOnIndex={0}
/>
),
[],
);
return (
<BottomSheetModal
ref={bottomSheetModalRef}
enableDynamicSizing
maxDynamicContentSize={600}
backdropComponent={renderBackdrop}
handleIndicatorStyle={{
backgroundColor: "white",
}}
backgroundStyle={{
backgroundColor: "#171717",
}}
>
<BottomSheetView style={{ paddingBottom: insets.bottom }}>
{currentItem && (
<WatchlistSheetContent item={currentItem} onClose={handleClose} />
)}
</BottomSheetView>
</BottomSheetModal>
);
},
);