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

MediaVideoPlayer.tsx

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