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),
})),
);

67
pnpm-lock.yaml generated
View File

@@ -55,6 +55,9 @@ importers:
expo:
specifier: ~50.0.5
version: 50.0.5(@babel/core@7.23.9)(@react-native/babel-preset@0.73.20)
expo-av:
specifier: ~13.10.5
version: 13.10.5(expo@50.0.5)
expo-build-properties:
specifier: ~0.11.1
version: 0.11.1(expo@50.0.5)
@@ -79,6 +82,9 @@ importers:
expo-web-browser:
specifier: ^12.8.2
version: 12.8.2(expo@50.0.5)
immer:
specifier: ^10.0.3
version: 10.0.3
nativewind:
specifier: ~4.0.23
version: 4.0.23(patch_hash=42qwizvrnoqgalbele35lpnaqi)(@babel/core@7.23.9)(react-native-reanimated@3.6.2)(react-native-safe-area-context@4.8.2)(react-native@0.73.2)(react@18.2.0)(tailwindcss@3.4.1)
@@ -112,15 +118,15 @@ importers:
react-native-screens:
specifier: ~3.29.0
version: 3.29.0(react-native@0.73.2)(react@18.2.0)
react-native-video:
specifier: 6.0.0-beta.5
version: 6.0.0-beta.5(react-native@0.73.2)(react@18.2.0)
react-native-web:
specifier: ^0.19.10
version: 0.19.10(react-dom@18.2.0)(react@18.2.0)
tailwind-merge:
specifier: ^2.2.1
version: 2.2.1
zustand:
specifier: ^4.4.7
version: 4.4.7(@types/react@18.2.52)(immer@10.0.3)(react@18.2.0)
devDependencies:
'@babel/core':
specifier: ^7.23.9
@@ -3193,7 +3199,6 @@ packages:
/@types/prop-types@15.7.11:
resolution: {integrity: sha512-ga8y9v9uyeiLdpKddhxYQkxNDrfvuPrlFb0N1qnZZByvcElJaXthF1UhvCh9TLWJBEHeNtdnbysW7Y6Uq8CVng==}
dev: true
/@types/react@18.2.52:
resolution: {integrity: sha512-E/YjWh3tH+qsLKaUzgpZb5AY0ChVa+ZJzF7ogehVILrFpdQk6nC/WXOv0bfFEABbXbgNxLBGU7IIZByPKb6eBw==}
@@ -3201,11 +3206,9 @@ packages:
'@types/prop-types': 15.7.11
'@types/scheduler': 0.16.8
csstype: 3.1.3
dev: true
/@types/scheduler@0.16.8:
resolution: {integrity: sha512-WZLiwShhwLRmeV6zH+GkbOFT6Z6VklCItrDioxUnv+u4Ll+8vKeFySoFyK/0ctcRpOmwAicELfmys1sDc/Rw+A==}
dev: true
/@types/semver@7.5.6:
resolution: {integrity: sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A==}
@@ -4700,7 +4703,6 @@ packages:
/csstype@3.1.3:
resolution: {integrity: sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==}
dev: true
/dag-map@1.0.2:
resolution: {integrity: sha512-+LSAiGFwQ9dRnRdOeaj7g47ZFJcOUPukAP8J3A3fuZ1g9Y44BG+P1sgApjLXTQPOzC4+7S9Wr8kXsfpINM4jpw==}
@@ -5501,6 +5503,14 @@ packages:
- supports-color
dev: false
/expo-av@13.10.5(expo@50.0.5):
resolution: {integrity: sha512-w45oCoe+8PunDeM0rh/Ut6UaGh7OjEJOCjAiQy3nCxpA8FaXB17KaqpsvkAXIMvceHYWndH8+D29esUTS6wEsA==}
peerDependencies:
expo: '*'
dependencies:
expo: 50.0.5(@babel/core@7.23.9)(@react-native/babel-preset@0.73.20)
dev: false
/expo-build-properties@0.11.1(expo@50.0.5):
resolution: {integrity: sha512-m4j4aEjFaDuBE6KWYMxDhWgLzzSmpE7uHKAwtvXyNmRK+6JKF0gjiXi0sXgI5ngNppDQpsyPFMvqG7uQpRuCuw==}
peerDependencies:
@@ -6400,6 +6410,10 @@ packages:
queue: 6.0.2
dev: false
/immer@10.0.3:
resolution: {integrity: sha512-pwupu3eWfouuaowscykeckFmVTpqbzW+rXFCX8rQLkZzM9ftBmU/++Ra+o+L27mz03zJTlyV4UUr+fdKNffo4A==}
dev: false
/import-fresh@2.0.0:
resolution: {integrity: sha512-eZ5H8rcgYazHbKC3PG4ClHNykCSxtAhxSSEM+2mb+7evD2CKF5V7c0dNum7AdpDh0ZdICwZY9sRSn8f+KH96sg==}
engines: {node: '>=4'}
@@ -9021,16 +9035,6 @@ packages:
warn-once: 0.1.1
dev: false
/react-native-video@6.0.0-beta.5(react-native@0.73.2)(react@18.2.0):
resolution: {integrity: sha512-dAfIXvtxsMI8TE3Q+1MHTP1brq3/V2VsPKVDtU8E+JcF963y5upnBb8JFiG8Yl4s4qAoQum2P02fZE30stQOHg==}
peerDependencies:
react: '*'
react-native: '*'
dependencies:
react: 18.2.0
react-native: 0.73.2(@babel/core@7.23.9)(@babel/preset-env@7.23.9)(react@18.2.0)
dev: false
/react-native-web@0.19.10(react-dom@18.2.0)(react@18.2.0):
resolution: {integrity: sha512-IQoHiTQq8egBCVVwmTrYcFLgEFyb4LMZYEktHn4k22JMk9+QTCEz5WTfvr+jdNoeqj/7rtE81xgowKbfGO74qg==}
peerDependencies:
@@ -10543,6 +10547,14 @@ packages:
react: 18.2.0
dev: false
/use-sync-external-store@1.2.0(react@18.2.0):
resolution: {integrity: sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0
dependencies:
react: 18.2.0
dev: false
/util-deprecate@1.0.2:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
@@ -10913,3 +10925,24 @@ packages:
/yocto-queue@0.1.0:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'}
/zustand@4.4.7(@types/react@18.2.52)(immer@10.0.3)(react@18.2.0):
resolution: {integrity: sha512-QFJWJMdlETcI69paJwhSMJz7PPWjVP8Sjhclxmxmxv/RYI7ZOvR5BHX+ktH0we9gTWQMxcne8q1OY8xxz604gw==}
engines: {node: '>=12.7.0'}
peerDependencies:
'@types/react': '>=16.8'
immer: '>=9.0'
react: '>=16.8'
peerDependenciesMeta:
'@types/react':
optional: true
immer:
optional: true
react:
optional: true
dependencies:
'@types/react': 18.2.52
immer: 10.0.3
react: 18.2.0
use-sync-external-store: 1.2.0(react@18.2.0)
dev: false

View File

@@ -7,6 +7,7 @@ const config = {
],
rules: {
"react/prop-types": "off",
"@typescript-eslint/unbound-method": "off",
},
globals: {
React: "writable",