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

MediaVideoPlayer.tsx

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