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

MediaVideoPlayer.tsx

190 lines7.9 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 // RN reports both leaving the app and Android fullscreen as background; native handling distinguishes them.
50 const subscription = AppState.addEventListener("change", (state) => {
51 active.current = focused && !paused && state === "active";
52 if (state === "inactive" || (state === "background" && !fullscreen.current)) player.pause();
53 });
54 return () => subscription.remove();
55 }, [focused, player, paused]);
56​
57 useEffect(() => {
58 const controller = new AbortController();
59 setLoadState("pending");
60 // A renewed signature is used on Retry, not as a reason to reset the native player.
61 void loadSource(controller.signal).then(
62 () => {
63 if (!controller.signal.aborted) setLoadState("complete");
64 },
65 () => {
66 if (!controller.signal.aborted) setLoadState("error");
67 },
68 );
69 return () => controller.abort();
70 }, [player, props.playRequested, attempt]);
71​
72 return (
73 <View collapsable={false} style={{ flex: 1 }}>
74 <VideoView
75 player={player}
76 style={{ width: "100%", height: "100%" }}
77 surfaceType="textureView"
78 nativeControls
79 contentFit="contain"
80 fullscreenOptions={{ enable: true }}
81 onFullscreenEnter={() => {
82 fullscreen.current = true;
83 }}
84 onFullscreenExit={() => {
85 fullscreen.current = false;
86 }}
87 allowsPictureInPicture={false}
88 />
89 {loadState === "error" || (loadState === "complete" && status === "error") ? (
90 <View className="absolute inset-0 items-center justify-center gap-2 bg-black px-4">
91 <AppText className="text-center text-sm text-white/80">Video unavailable</AppText>
92 <Pressable
93 accessibilityRole="button"
94 accessibilityLabel="Retry video"
95 onPress={() => setAttempt((value) => value + 1)}
96 className="min-h-11 justify-center px-4"
97 >
98 <AppText className="text-sm text-white">Retry</AppText>
99 </Pressable>
100 </View>
101 ) : loadState === "pending" || status === "loading" ? (
102 <View pointerEvents="none" className="absolute inset-0 items-center justify-center">
103 <AppActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
104 </View>
105 ) : null}
106 </View>
107 );
109​
110interface MediaVideoPlayerProps {
111 readonly uri: string | null;
112 readonly resolvePlaybackUri?: () => Promise<string | null>;
113 readonly name: string;
114 readonly thumbnailKey: string;
115 readonly thumbnailVisible?: boolean;
116 readonly unavailable?: boolean;
117 readonly expanded?: boolean;
118 readonly autoPlay?: boolean;
119 readonly paused?: boolean;
120 readonly actionsSource?: MediaActionsSource;
122​
123function MediaVideoPlayerContent(props: MediaVideoPlayerProps) {
124 const mediaActions = useMediaActions(props.actionsSource);
125 const [playbackUri, setPlaybackUri] = useState<string | null>(props.expanded ? props.uri : null);
126 // Keep an opened player mounted while signing or reconnecting temporarily has no usable URL.
127 if (playbackUri === null && props.expanded && props.uri !== null) setPlaybackUri(props.uri);
128​
129 return (
130 <View
131 collapsable={false}
132 className="overflow-hidden rounded-[10px] bg-black"
133 style={props.expanded ? { flex: 1 } : { width: "100%", maxWidth: 480, aspectRatio: 16 / 9 }}
134 >
135 {playbackUri ? (
136 <LoadedMediaVideo
137 uri={props.uri ?? playbackUri}
138 resolvePlaybackUri={props.resolvePlaybackUri}
139 playRequested={!props.expanded || props.autoPlay === true}
140 paused={(props.paused ?? false) || mediaActions.sharing}
141 />
142 ) : (
143 <MediaActionsMenu media={mediaActions} inModal={props.expanded} style={{ flex: 1 }}>
144 <Pressable
145 accessibilityRole="button"
146 accessibilityLabel={`Play ${props.name}`}
147 accessibilityHint={
148 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
149 }
150 accessibilityState={{ disabled: props.uri === null || props.unavailable === true }}
151 // Stays pressable so the long-press menu still opens on a failed or unsigned tile.
152 onPress={() => {
153 if (props.uri !== null && !props.unavailable) setPlaybackUri(props.uri);
154 }}
155 className="flex-1 items-center justify-center px-4"
156 >
157 {!props.unavailable ? (
158 <VideoThumbnailImage
159 cacheKey={props.thumbnailKey}
160 source={props.thumbnailVisible === false ? null : props.uri}
161 contentFit="contain"
162 />
163 ) : null}
164 {props.unavailable ? (
165 <AppText className="text-sm text-white/80">Video unavailable</AppText>
166 ) : props.uri === null ? (
167 <AppActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
168 ) : (
169 <View className="size-12 items-center justify-center rounded-full bg-black/60">
170 <SymbolView name="play" size={28} tintColor="#ffffff" type="monochrome" />
171 </View>
172 )}
173 {props.uri !== null && !props.unavailable ? (
174 <AppText
175 className="absolute right-2 bottom-2 max-w-[75%] rounded bg-black/60 px-2 py-1 text-right text-xs text-white"
176 numberOfLines={1}
177 >
178 {props.name}
179 </AppText>
180 ) : null}
181 </Pressable>
182 </MediaActionsMenu>
183 )}
184 </View>
185 );
187​
188export function MediaVideoPlayer(props: MediaVideoPlayerProps) {
189 return <MediaVideoPlayerContent key={props.thumbnailKey} {...props} />;