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