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