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 autoPlay?: boolean;
105 readonly paused?: boolean;
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 || props.autoPlay === true}
126 paused={(props.paused ?? false) || mediaActions.sharing}
127 />
128 ) : (
129 <MediaActionsMenu media={mediaActions} inModal={props.expanded} style={{ flex: 1 }}>
130 <Pressable
131 accessibilityRole="button"
132 accessibilityLabel={`Play ${props.name}`}
133 accessibilityHint={
134 mediaActions.actions.length > 0 ? "Touch and hold for media actions" : undefined
135 }
136 accessibilityState={{ disabled: props.uri === null || props.unavailable === true }}
137 // Stays pressable so the long-press menu still opens on a failed or unsigned tile.
138 onPress={() => {
139 if (props.uri !== null && !props.unavailable) setPlaybackUri(props.uri);
140 }}
141 className="flex-1 items-center justify-center px-4"
142 >
143 {!props.unavailable ? (
144 <VideoThumbnailImage
145 cacheKey={props.thumbnailKey}
146 source={props.thumbnailVisible === false ? null : props.uri}
147 contentFit="contain"
148 />
149 ) : null}
150 {props.unavailable ? (
151 <AppText className="text-sm text-white/80">Video unavailable</AppText>
152 ) : props.uri === null ? (
153 <ActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
154 ) : (
155 <View className="size-12 items-center justify-center rounded-full bg-black/60">
156 <SymbolView name="play" size={28} tintColor="#ffffff" type="monochrome" />
157 </View>
158 )}
159 {props.uri !== null && !props.unavailable ? (
160 <AppText
161 className="absolute right-2 bottom-2 max-w-[75%] rounded bg-black/60 px-2 py-1 text-right text-xs text-white"
162 numberOfLines={1}
163 >
164 {props.name}
165 </AppText>
166 ) : null}
167 </Pressable>
168 </MediaActionsMenu>
169 )}
170 </View>
171 );
172}
173
174export function MediaVideoPlayer(props: MediaVideoPlayerProps) {
175 return <MediaVideoPlayerContent key={props.thumbnailKey} {...props} />;
176}