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

VideoPreviewModal.tsx

254 lines8.6 KB

1import { useIsFocused } from "@react-navigation/native";
2import { videoMimeType } from "@t3tools/shared/video";
3import { useEvent } from "expo";
4import { useVideoPlayer, VideoView } from "expo-video";
5import { useEffect, useRef, useState } from "react";
6import {
7 ActivityIndicator,
8 AppState,
9 Keyboard,
10 Modal,
11 Pressable,
12 StyleSheet,
13 View,
14} from "react-native";
15import { useSafeAreaInsets } from "react-native-safe-area-context";
16​
17import {
18 downloadAttachmentForPreview,
19 type AttachmentPreviewFile,
20} from "../lib/attachmentDownload";
21import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
22import type { AttachmentVideoPreviewSource, VideoPreviewSource } from "../lib/videoPreviewSource";
23import { useAssetUrlState } from "../state/assets";
24import { usePreparedConnection } from "../state/session";
25import { SymbolView } from "./AppSymbol";
26import { AppText } from "./AppText";
27import { MediaVideoPreviewModal } from "./MediaVideoPreviewModal";
28​
29export type { VideoPreviewSource } from "../lib/videoPreviewSource";
30​
31function VideoPlayback(props: { readonly file: AttachmentPreviewFile }) {
32 const player = useVideoPlayer(props.file.uri, (player) => {
33 player.staysActiveInBackground = false;
34 if (AppState.currentState === "active") player.play();
35 });
36 const { status } = useEvent(player, "statusChange", { status: player.status });
37 const shareControllerRef = useRef<AbortController | null>(null);
38 const [sharing, setSharing] = useState(false);
39 const [shareError, setShareError] = useState<string | null>(null);
40​
41 useEffect(
42 () => () => {
43 shareControllerRef.current?.abort();
44 shareControllerRef.current = null;
45 },
46 [],
47 );
48​
49 const onShare = () => {
50 if (shareControllerRef.current) return;
51 player.pause();
52 const controller = new AbortController();
53 shareControllerRef.current = controller;
54 setSharing(true);
55 setShareError(null);
56 void props.file
57 .share(controller.signal)
58 .catch((error: unknown) => {
59 if (!controller.signal.aborted) {
60 setShareError(error instanceof Error ? error.message : "Could not share this video.");
61 }
62 })
63 .finally(() => {
64 if (shareControllerRef.current === controller) {
65 shareControllerRef.current = null;
66 setSharing(false);
67 }
68 });
69 };
70​
71 return (
72 <>
73 <View className="flex-1 items-center justify-center">
74 {status === "error" ? (
75 <AppText className="px-6 text-center text-base text-white/80">
76 This video couldn't be played on this device. You can save or share the original file.
77 </AppText>
78 ) : (
79 <>
80 <VideoView
81 player={player}
82 style={StyleSheet.absoluteFill}
83 nativeControls
84 contentFit="contain"
85 fullscreenOptions={{ enable: true }}
86 allowsPictureInPicture={false}
87 />
88 {status === "loading" ? (
89 <ActivityIndicator color="#ffffff" accessibilityLabel="Loading video" />
90 ) : null}
91 </>
92 )}
93 </View>
94 <Pressable
95 accessibilityRole="button"
96 accessibilityLabel="Save or share video"
97 accessibilityState={{ disabled: sharing, busy: sharing }}
98 disabled={sharing}
99 onPress={onShare}
100 className="mx-4 my-3 min-h-12 items-center justify-center rounded-xl bg-white/15 px-4"
101 >
102 <AppText className="font-t3-medium text-base text-white">
103 {sharing ? "Opening share sheet..." : "Save or share video"}
104 </AppText>
105 </Pressable>
106 {shareError ? (
107 <AppText accessibilityRole="alert" className="px-4 pb-3 text-sm text-white/80">
108 {shareError}
109 </AppText>
110 ) : null}
111 </>
112 );
114​
115function OpenVideoPreviewModal(props: {
116 readonly source: AttachmentVideoPreviewSource;
117 readonly onRequestClose: () => void;
118}) {
119 const { source } = props;
120 const { attachment } = source;
121 const insets = useSafeAreaInsets();
122 const environmentId = source.type === "remote" ? source.environmentId : null;
123 const preparedConnection = usePreparedConnection(environmentId);
124 const fileUri = source.type === "local" ? source.attachment.fileUri : null;
125 const mimeType = videoMimeType(attachment) ?? attachment.mimeType;
126 const assetUrl = useAssetUrlState(
127 environmentId,
128 source.type === "remote"
129 ? { _tag: "attachment", attachmentId: attachment.id, fileName: attachment.name, mimeType }
130 : null,
131 );
132 const [downloadUrl, setDownloadUrl] = useState<string | null>(null);
133 const [file, setFile] = useState<AttachmentPreviewFile | null>(null);
134 const [failure, setFailure] = useState<string | null>(null);
135​
136 useEffect(() => Keyboard.dismiss(), []);
137 useEffect(() => {
138 if (environmentId !== null && downloadUrl === null && assetUrl._tag === "Success") {
139 setDownloadUrl(assetUrl.url);
140 }
141 }, [environmentId, downloadUrl, assetUrl]);
142​
143 useEffect(() => {
144 if (source.type === "remote" && downloadUrl === null) return;
145 const controller = new AbortController();
146 let preview: AttachmentPreviewFile | null = null;
147 setFile(null);
148 setFailure(null);
149 const loading =
150 source.type === "local"
151 ? loadLocalAttachmentPreview(source.attachment, controller.signal)
152 : downloadAttachmentForPreview({
153 url: downloadUrl!,
154 attachment: { name: attachment.name, mimeType },
155 signal: controller.signal,
156 });
157 void loading.then(
158 (loaded) => {
159 if (controller.signal.aborted) {
160 loaded?.dispose();
161 return;
162 }
163 preview = loaded;
164 setFile(loaded);
165 },
166 (error: unknown) => {
167 if (!controller.signal.aborted) {
168 setFailure(error instanceof Error ? error.message : "Could not load this video.");
169 }
170 },
171 );
172 return () => {
173 controller.abort();
174 preview?.dispose();
175 };
176 }, [source.type, environmentId, attachment.id, attachment.name, mimeType, fileUri, downloadUrl]);
177​
178 const loadError =
179 failure ??
180 (environmentId !== null && downloadUrl === null
181 ? preparedConnection._tag === "None"
182 ? "This environment is disconnected. Reconnect and open the video again."
183 : assetUrl._tag === "Failure"
184 ? "Could not load this video. Check the connection to this environment and try again."
185 : null
186 : null);
187​
188 return (
189 <Modal
190 visible
191 animationType="fade"
192 presentationStyle="fullScreen"
193 onRequestClose={props.onRequestClose}
194 statusBarTranslucent
195 navigationBarTranslucent
196 >
197 <View
198 className="flex-1 bg-black"
199 style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
200 >
201 <View className="min-h-14 flex-row items-center gap-3 pl-4 pr-2">
202 <AppText className="flex-1 font-t3-medium text-base text-white" numberOfLines={2}>
203 {attachment.name}
204 </AppText>
205 <Pressable
206 accessibilityRole="button"
207 accessibilityLabel="Close video"
208 onPress={props.onRequestClose}
209 className="size-12 items-center justify-center"
210 >
211 <SymbolView name="xmark" size={20} tintColor="#ffffff" type="monochrome" />
212 </Pressable>
213 </View>
214 {file ? (
215 <VideoPlayback key={file.uri} file={file} />
216 ) : (
217 <View className="flex-1 items-center justify-center gap-3 px-6">
218 {loadError ? (
219 <AppText accessibilityRole="alert" className="text-center text-base text-white/80">
220 {loadError}
221 </AppText>
222 ) : (
223 <>
224 <ActivityIndicator color="#ffffff" />
225 <AppText className="text-sm text-white/80">Loading video...</AppText>
226 </>
227 )}
228 </View>
229 )}
230 </View>
231 </Modal>
232 );
234​
235export function VideoPreviewModal(props: {
236 readonly source: VideoPreviewSource | null;
237 readonly onRequestClose: () => void;
238}) {
239 const isFocused = useIsFocused();
240 const hasSource = props.source !== null;
241 useEffect(() => {
242 if (!isFocused && hasSource) props.onRequestClose();
243 }, [isFocused, hasSource, props.onRequestClose]);
244 const { source } = props;
245 if (source === null || !isFocused) return null;
246 if (source.type === "media") {
247 return <MediaVideoPreviewModal source={source} onRequestClose={props.onRequestClose} />;
248 }
249 const key =
250 source.type === "local"
251 ? `local:${source.attachment.id}:${source.attachment.fileUri}`
252 : `remote:${source.environmentId}:${source.attachment.id}`;
253 return <OpenVideoPreviewModal key={key} source={source} onRequestClose={props.onRequestClose} />;