introduce store with idle tracking

This commit is contained in:
Jorrin
2024-02-12 16:11:35 +01:00
parent 3d1a5a88f2
commit 094c0382a6
12 changed files with 234 additions and 176 deletions

View File

@@ -26,6 +26,7 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"expo": "~50.0.5",
"expo-av": "~13.10.5",
"expo-build-properties": "~0.11.1",
"expo-constants": "~15.4.5",
"expo-linking": "~6.2.2",
@@ -34,6 +35,7 @@
"expo-splash-screen": "~0.26.4",
"expo-status-bar": "~1.11.1",
"expo-web-browser": "^12.8.2",
"immer": "^10.0.3",
"nativewind": "~4.0.23",
"react": "18.2.0",
"react-dom": "18.2.0",
@@ -45,9 +47,9 @@
"react-native-reanimated": "~3.6.2",
"react-native-safe-area-context": "~4.8.2",
"react-native-screens": "~3.29.0",
"react-native-video": "6.0.0-beta.5",
"react-native-web": "^0.19.10",
"tailwind-merge": "^2.2.1"
"tailwind-merge": "^2.2.1",
"zustand": "^4.4.7"
},
"devDependencies": {
"@babel/core": "^7.23.9",

View File

@@ -1,11 +1,7 @@
import type {
ISO639_1,
ReactVideoSource,
TextTracks,
} from "react-native-video";
import type { AVPlaybackSource } from "expo-av";
import React, { useEffect, useState } from "react";
import { ActivityIndicator, Platform, StyleSheet, View } from "react-native";
import Video, { TextTracksType } from "react-native-video";
import { ActivityIndicator, StyleSheet, View } from "react-native";
import { ResizeMode, Video } from "expo-av";
import { useLocalSearchParams, useRouter } from "expo-router";
import * as ScreenOrientation from "expo-screen-orientation";
@@ -18,18 +14,14 @@ import { fetchMediaDetails } from "@movie-web/tmdb";
import type { ItemData } from "~/components/item/item";
import { Header } from "~/components/player/Header";
import { PlayerProvider, usePlayer } from "~/context/player.context";
import { usePlayerStore } from "~/stores/player/store";
export default function VideoPlayerWrapper() {
const params = useLocalSearchParams();
const data = params.data
? (JSON.parse(params.data as string) as ItemData)
: null;
return (
<PlayerProvider>
<VideoPlayer data={data} />
</PlayerProvider>
);
return <VideoPlayer data={data} />;
}
interface VideoPlayerProps {
@@ -37,16 +29,18 @@ interface VideoPlayerProps {
}
const VideoPlayer: React.FC<VideoPlayerProps> = ({ data }) => {
const [videoSrc, setVideoSrc] = useState<ReactVideoSource>();
const [_textTracks, setTextTracks] = useState<TextTracks>([]);
const [videoSrc, setVideoSrc] = useState<AVPlaybackSource>();
const [isLoading, setIsLoading] = useState(true);
const router = useRouter();
const {
setVideoRef,
unlockOrientation,
presentFullscreenPlayer,
dismissFullscreenPlayer,
} = usePlayer();
const setVideoRef = usePlayerStore((state) => state.setVideoRef);
const setStatus = usePlayerStore((state) => state.setStatus);
const setIsIdle = usePlayerStore((state) => state.setIsIdle);
const presentFullscreenPlayer = usePlayerStore(
(state) => state.presentFullscreenPlayer,
);
const dismissFullscreenPlayer = usePlayerStore(
(state) => state.dismissFullscreenPlayer,
);
useEffect(() => {
const initializePlayer = async () => {
@@ -98,11 +92,11 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({ data }) => {
url = stream.playlist;
}
setTextTracks(
stream.captions && stream.captions.length > 0
? convertCaptionsToTextTracks(stream.captions)
: [],
);
// setTextTracks(
// stream.captions && stream.captions.length > 0
// ? convertCaptionsToTextTracks(stream.captions)
// : [],
// );
setVideoSrc({
uri: url,
@@ -127,15 +121,8 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({ data }) => {
return () => {
void dismissFullscreenPlayer();
void unlockOrientation();
};
}, [
data,
dismissFullscreenPlayer,
presentFullscreenPlayer,
router,
unlockOrientation,
]);
}, [data, dismissFullscreenPlayer, presentFullscreenPlayer, router]);
const onVideoLoadStart = () => {
setIsLoading(true);
@@ -150,58 +137,56 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({ data }) => {
<Video
ref={setVideoRef}
source={videoSrc}
// textTracks={textTracks} // breaks playback on iOS, see pr body
fullscreen
fullscreenOrientation="landscape"
paused={false}
controls
useSecureView
shouldPlay
resizeMode={ResizeMode.CONTAIN}
onLoadStart={onVideoLoadStart}
onReadyForDisplay={onReadyForDisplay}
style={styles.backgroundVideo}
onPlaybackStatusUpdate={setStatus}
style={styles.video}
onTouchStart={() => setIsIdle(false)}
/>
{isLoading && <ActivityIndicator size="large" color="#0000ff" />}
{!isLoading && <Header title={data!.title} />}
{!isLoading && data && <Header title={data.title} />}
</View>
);
};
interface Caption {
type: "srt" | "vtt";
id: string;
url: string;
hasCorsRestrictions: boolean;
language: string;
}
// interface Caption {
// type: "srt" | "vtt";
// id: string;
// url: string;
// hasCorsRestrictions: boolean;
// language: string;
// }
const captionTypeToTextTracksType = {
srt: TextTracksType.SUBRIP,
vtt: TextTracksType.VTT,
};
// const captionTypeToTextTracksType = {
// srt: TextTracksType.SUBRIP,
// vtt: TextTracksType.VTT,
// };
function convertCaptionsToTextTracks(captions: Caption[]): TextTracks {
return captions
.map((caption) => {
if (Platform.OS === "ios" && caption.type !== "vtt") {
return null;
}
// function convertCaptionsToTextTracks(captions: Caption[]): TextTracks {
// return captions
// .map((caption) => {
// if (Platform.OS === "ios" && caption.type !== "vtt") {
// return null;
// }
return {
title: caption.language,
language: caption.language as ISO639_1,
type: captionTypeToTextTracksType[caption.type],
uri: caption.url,
};
})
.filter(Boolean) as TextTracks;
}
// return {
// title: caption.language,
// language: caption.language as ISO639_1,
// type: captionTypeToTextTracksType[caption.type],
// uri: caption.url,
// };
// })
// .filter(Boolean) as TextTracks;
// }
const styles = StyleSheet.create({
backgroundVideo: {
video: {
position: "absolute",
top: 0,
left: 0,
bottom: 0,
left: 0,
right: 0,
},
});

View File

@@ -1,12 +1,12 @@
import { useRouter } from "expo-router";
import { Ionicons } from "@expo/vector-icons";
import { usePlayer } from "~/context/player.context";
import { usePlayerStore } from "~/stores/player/store";
export const BackButton = ({
className,
}: Partial<React.ComponentProps<typeof Ionicons>>) => {
const { unlockOrientation } = usePlayer();
const unlockOrientation = usePlayerStore((state) => state.unlockOrientation);
const router = useRouter();
return (

View File

@@ -0,0 +1,13 @@
import { View } from "react-native";
import { usePlayerStore } from "~/stores/player/store";
interface ControlsProps {
children: React.ReactNode;
}
export const Controls = ({ children }: ControlsProps) => {
const idle = usePlayerStore((state) => state.interface.isIdle);
return <View className="flex-1 items-center">{!idle && children}</View>;
};

View File

@@ -1,9 +1,9 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { Image, View } from "react-native";
import Icon from "../../../assets/images/icon-transparent.png";
import { Text } from "../ui/Text";
import { BackButton } from "./BackButton";
import { Controls } from "./Controls";
interface HeaderProps {
title: string;
@@ -11,13 +11,15 @@ interface HeaderProps {
export const Header = ({ title }: HeaderProps) => {
return (
<View className="absolute top-0 flex w-full flex-row items-center justify-between px-6 pt-6">
<BackButton className="w-36" />
<Text className="font-bold">{title}</Text>
<View className="flex w-36 flex-row items-center justify-center gap-2 space-x-2 rounded-full bg-secondary-300 px-4 py-2 opacity-80">
<Image source={Icon} className="h-6 w-6" />
<Text className="font-bold">movie-web</Text>
<Controls>
<View className="absolute top-0 flex w-full flex-row items-center justify-between px-6 pt-6">
<BackButton className="w-36" />
<Text className="font-bold">{title}</Text>
<View className="flex w-36 flex-row items-center justify-center gap-2 space-x-2 rounded-full bg-secondary-300 px-4 py-2 opacity-80">
<Image source={Icon} className="h-6 w-6" />
<Text className="font-bold">movie-web</Text>
</View>
</View>
</View>
</Controls>
);
};

View File

@@ -1,77 +0,0 @@
import type { VideoRef } from "react-native-video";
import React, { createContext, useCallback, useContext, useState } from "react";
import * as ScreenOrientation from "expo-screen-orientation";
interface PlayerContextProps {
videoRef: VideoRef | null;
setVideoRef: (ref: VideoRef | null) => void;
lockOrientation: () => Promise<void>;
unlockOrientation: () => Promise<void>;
presentFullscreenPlayer: () => Promise<void>;
dismissFullscreenPlayer: () => Promise<void>;
}
interface PlayerProviderProps {
children: React.ReactNode;
}
const PlayerContext = createContext<PlayerContextProps | undefined>(undefined);
export const PlayerProvider = ({ children }: PlayerProviderProps) => {
const [internalVideoRef, setInternalVideoRef] = useState<VideoRef | null>(
null,
);
const setVideoRef = useCallback((ref: VideoRef | null) => {
setInternalVideoRef(ref);
}, []);
const lockOrientation = useCallback(async () => {
await ScreenOrientation.lockAsync(
ScreenOrientation.OrientationLock.LANDSCAPE,
);
}, []);
const unlockOrientation = useCallback(async () => {
await ScreenOrientation.lockAsync(
ScreenOrientation.OrientationLock.PORTRAIT_UP,
);
}, []);
const presentFullscreenPlayer = useCallback(async () => {
if (internalVideoRef) {
internalVideoRef.presentFullscreenPlayer();
await lockOrientation();
}
}, [internalVideoRef, lockOrientation]);
const dismissFullscreenPlayer = useCallback(async () => {
if (internalVideoRef) {
internalVideoRef.dismissFullscreenPlayer();
await unlockOrientation();
}
}, [internalVideoRef, unlockOrientation]);
const contextValue: PlayerContextProps = {
videoRef: internalVideoRef,
setVideoRef,
lockOrientation,
unlockOrientation,
presentFullscreenPlayer,
dismissFullscreenPlayer,
};
return (
<PlayerContext.Provider value={contextValue}>
{children}
</PlayerContext.Provider>
);
};
export const usePlayer = (): PlayerContextProps => {
const context = useContext(PlayerContext);
if (!context) {
throw new Error("usePlayer must be used within a PlayerProvider");
}
return context;
};

View File

@@ -0,0 +1,48 @@
import * as ScreenOrientation from "expo-screen-orientation";
import type { MakeSlice } from "./types";
export interface InterfaceSlice {
interface: {
isIdle: boolean;
};
setIsIdle(state: boolean): void;
lockOrientation: () => Promise<void>;
unlockOrientation: () => Promise<void>;
presentFullscreenPlayer: () => Promise<void>;
dismissFullscreenPlayer: () => Promise<void>;
}
export const createInterfaceSlice: MakeSlice<InterfaceSlice> = (set, get) => ({
interface: {
isIdle: true,
},
setIsIdle: (state) => {
set((s) => {
setTimeout(() => {
if (get().interface.isIdle === false) {
set((s) => {
s.interface.isIdle = true;
});
}
}, 6000);
s.interface.isIdle = state;
});
},
lockOrientation: async () => {
await ScreenOrientation.lockAsync(
ScreenOrientation.OrientationLock.LANDSCAPE,
);
},
unlockOrientation: async () => {
await ScreenOrientation.lockAsync(
ScreenOrientation.OrientationLock.PORTRAIT_UP,
);
},
presentFullscreenPlayer: async () => {
await get().lockOrientation();
},
dismissFullscreenPlayer: async () => {
await get().unlockOrientation();
},
});

View File

@@ -0,0 +1,13 @@
import type { StateCreator } from "zustand";
import type { InterfaceSlice } from "./interface";
import type { VideoSlice } from "./video";
export type AllSlices = InterfaceSlice & VideoSlice;
export type MakeSlice<Slice> = StateCreator<
AllSlices,
[["zustand/immer", never]],
[],
Slice
>;

View File

@@ -0,0 +1,25 @@
import type { AVPlaybackStatus, Video } from "expo-av";
import type { MakeSlice } from "./types";
export interface VideoSlice {
videoRef: Video | null;
status: AVPlaybackStatus | null;
setVideoRef(ref: Video | null): void;
setStatus(status: AVPlaybackStatus | null): void;
}
export const createVideoSlice: MakeSlice<VideoSlice> = (set) => ({
videoRef: null,
status: null,
setVideoRef: (ref) => {
set({ videoRef: ref });
},
setStatus: (status) => {
set((s) => {
s.status = status;
});
},
});

View File

@@ -0,0 +1,13 @@
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import type { AllSlices } from "./slices/types";
import { createInterfaceSlice } from "./slices/interface";
import { createVideoSlice } from "./slices/video";
export const usePlayerStore = create(
immer<AllSlices>((...a) => ({
...createInterfaceSlice(...a),
...createVideoSlice(...a),
})),
);