Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MediaVideoPlayer.tsx

191 lines8.0 KB

1import { useIsFocused } from "@react-navigation/native";
2import { useEvent } from "expo";
3import { useVideoPlayer, VideoView } from "expo-video";
4import { useEffect, useEffectEvent, useRef, useState } from "react";
5import { AppState, Pressable, View } from "react-native";
6​
7import { AppActivityIndicator } from "./ui/AppActivityIndicator";
8import { AppText } from "./ui/AppText";
9import { SymbolView } from "./ui/AppSymbol";
10import { VideoThumbnailImage } from "./VideoThumbnailImage";
11import { useMediaActions } from "../state/mediaActions";
12import { type MediaActionsSource } from "../lib/mediaActionsSource";
13import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../lib/videoAudioSession";
14import { MediaActionsMenu } from "./MediaActionsMenu";
15​
16function LoadedMediaVideo(props: {
17 readonly uri: string;
18 readonly resolvePlaybackUri?: () => Promise<string | null>;
19 readonly playRequested: boolean;
20 readonly paused: boolean;
21}) {
22 const focused = useIsFocused();
23 const fullscreenVideoOpen = useFullscreenVideoOpen();
24 const paused = props.paused || fullscreenVideoOpen;
25 const active = useRef(focused && AppState.currentState === "active");
26 const fullscreen = useRef(false);
27 const [attempt, setAttempt] = useState(0);
28 // Expo's Android player also reports completed playback as idle.
29 const [loadState, setLoadState] = useState<"pending" | "complete" | "error">("pending");
30 const player = useVideoPlayer(null, (player) => {
31 player.staysActiveInBackground = false;
32 player.bufferOptions = { preferredForwardBufferDuration: 5 };
33 });
34 const { status } = useEvent(player, "statusChange", { status: player.status });
35 const { isPlaying } = useEvent(player, "playingChange", { isPlaying: player.playing });
36 useMediaAudioSessionHold(isPlaying);
37 const loadSource = useEffectEvent(async (signal: AbortSignal) => {
38 const uri = props.resolvePlaybackUri ? await props.resolvePlaybackUri() : props.uri;
39 if (signal.aborted) return;
40 if (uri === null) throw new Error("Video unavailable");
41 player.pause();
42 await player.replaceAsync({ uri, contentType: "progressive" });
43 if (!signal.aborted && props.playRequested && active.current) player.play();
44 });
45​
46 useEffect(() => {
47 active.current = focused && !paused && AppState.currentState === "active";
48 if (!focused || paused || (!active.current && !fullscreen.current)) player.pause();
49 // Native background handling distinguishes Android's fullscreen activity
50 // from leaving the app; React Native reports both as background.
51 const subscription = AppState.addEventListener("change", (state) => {
52 active.current = focused && !paused && state === "active";
53 if (state === "inactive" || (state === "background" && !fullscreen.current)) player.pause();
54 });
55 return () => subscription.remove();
56 }, [focused, player, paused]);
57​
58 useEffect(() => {
59 const controller = new AbortController();
60 setLoadState("pending");
61 // A renewed signature is used on Retry, not as a reason to reset the native player.
62 void loadSource(controller.signal).then(
63 () => {
64 if (!controller.signal.aborted) setLoadState("complete");
65 },
66 () => {
67 if (!controller.signal.aborted) setLoadState("error");
68 },
69 );
70 return () => controller.abort();
71 }, [player, props.playRequested, attempt]);
72​
73 return (
74 <View collapsable={false} style={{ flex: 1 }}>
75 <VideoView
76 player={player}
77 style={{ width: "100%", height: "100%" }}
78 surfaceType="textureView"
79 nativeControls
80 contentFit="contain"
81 fullscreenOptions={{ enable: true }}
82 onFullscreenEnter={() => {
83 fullscreen.current = true;
84 }}
85 onFullscreenExit={() => {
86 fullscreen.current = false;
87 }}
88 allowsPictureInPicture={false}
89 />
90 {loadState === "error" || (loadState === "complete" && status === "error") ? (
91 <View className="absolute inset-0 items-center justify-center gap-2 bg-black px-4">
92 <AppText className="text-center text-sm text-white/80">Video unavailable</AppText>
93 <Pressable
94 accessibilityRole="button"
95 accessibilityLabel="Retry video"
96 onPress={() => setAttempt((value) => value + 1)}
97 className="min-h-11 justify-center px-4"
98 >
99 <AppText className="text-sm text-white">Retry</AppText>
100 </Pressable>
101 </View>
102 ) : loadState === "pending" || status === "loading" ? (
103 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
104 <AppActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
105 </View>
106 ) : null}
107 </View>
108 );
110​
111interface MediaVideoPlayerProps {
112 readonly uri: string | null;
113 readonly resolvePlaybackUri?: () => Promise<string | null>;
114 readonly name: string;
115 readonly thumbnailKey: string;
116 readonly thumbnailVisible?: boolean;
117 readonly unavailable?: boolean;
118 readonly expanded?: boolean;
119 readonly autoPlay?: boolean;
120 readonly paused?: boolean;
121 readonly actionsSource?: MediaActionsSource;
123​
124function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
125 const mediaActions = useMediaActions(props.actionsSource);
126 const [playbackUri, setPlaybackUri] = useState<string | null>(props.expanded ? props.uri : null);
127 // Keep an opened player mounted while signing or reconnecting temporarily has no usable URL.
128 if (playbackUri === null && props.expanded && props.uri !== null) setPlaybackUri(props.uri);
129​
130 return (
131 <View
132 collapsable={false}
133 className="overflow-hidden rounded-[10px] bg-black"
134 style={props.expanded ? { flex: 1 } : { width: "100%", maxWidth: 480, aspectRatio: 16 / 9 }}
135 >
136 {playbackUri ? (
137 <LoadedMediaVideo
138 uri={props.uri ?? playbackUri}
139 resolvePlaybackUri={props.resolvePlaybackUri}
140 playRequested={!props.expanded || props.autoPlay === true}
141 paused={(props.paused ?? false) || mediaActions.sharing}
142 />
143 ) : (
144 <MediaActionsMenu media={mediaActions} inModal={props.expanded} style={{ flex: 1 }}>
145 <Pressable
146 accessibilityRole="button"
147 accessibilityLabel={`Play ${props.name}`}
148 accessibilityHint={
149 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
150 }
151 accessibilityState={{ disabled: props.uri === null || props.unavailable === true }}
152 // Stays pressable so the long-press menu still opens on a failed or unsigned tile.
153 onPress={() => {
154 if (props.uri !== null && !props.unavailable) setPlaybackUri(props.uri);
155 }}
156 className="flex-1 items-center justify-center px-4"
157 >
158 {!props.unavailable ? (
159 <VideoThumbnailImage
160 cacheKey={props.thumbnailKey}
161 source={props.thumbnailVisible === false ? null : props.uri}
162 contentFit="contain"
163 />
164 ) : null}
165 {props.unavailable ? (
166 <AppText className="text-sm text-white/80">Video unavailable</AppText>
167 ) : props.uri === null ? (
168 <AppActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
169 ) : (
170 <View className="size-12 items-center justify-center rounded-full bg-black/60">
171 <SymbolView name="play" size={28} tintColor="#ffffff" type="monochrome" />
172 </View>
173 )}
174 {props.uri !== null && !props.unavailable ? (
175 <AppText
176 className="absolute right-2 bottom-2 max-w-[75%] rounded bg-black/60 px-2 py-1 text-right text-xs text-white"
177 numberOfLines={1}
178 >
179 {props.name}
180 </AppText>
181 ) : null}
182 </Pressable>
183 </MediaActionsMenu>
184 )}
185 </View>
186 );
188​
189export function MediaVideoPlayer(props: MediaVideoPlayerProps) {
190 return <MediaVideoPlayerContent key={props.thumbnailKey} {...props} />;