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

VideoPreviewModal.tsx

228 lines7.8 KB

1import { useIsFocused } from "@react-navigation/native";
2import { videoMimeType } from "@t3tools/shared/video";
3import { useEffect, useRef, useState } from "react";
4import { ActivityIndicator, Keyboard, Modal, Pressable, View } from "react-native";
5import { useSafeAreaInsets } from "react-native-safe-area-context";
6​
7import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
8import { useMediaActions } from "../state/mediaActions";
9import { type MediaActionsSource } from "../lib/mediaActionsSource";
10import {
11 mediaVideoPreviewUri,
12 mediaVideoThumbnailKey,
13 type LocalVideoPreviewSource,
14 type MediaVideoPreviewSource,
15 type VideoPreviewSource,
16} from "../lib/videoPreviewSource";
17import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
18import { usePreparedConnection } from "../state/session";
19import { AppText } from "./AppText";
20import { SymbolView } from "./AppSymbol";
21import { MediaActionsMenu } from "./MediaActionsMenu";
22import { MediaSourceCaption } from "./MediaSourceCaption";
23import { MediaVideoPlayer } from "./MediaVideoPlayer";
24​
25export type { VideoPreviewSource } from "../lib/videoPreviewSource";
26​
27interface PlaybackState {
28 readonly uri: string | null;
29 readonly resolvePlaybackUri?: () => Promise<string | null>;
30 readonly unavailable: boolean;
31 readonly error: string | null;
32 readonly actionsSource: MediaActionsSource | undefined;
34​
35function useMediaPlayback(source: MediaVideoPreviewSource): PlaybackState {
36 const environmentId = "environmentId" in source ? source.environmentId : null;
37 const resource = "resource" in source ? source.resource : null;
38 const connection = usePreparedConnection(environmentId);
39 const asset = useAssetUrlState(environmentId, resource);
40 const refreshAssetUrl = useRefreshAssetUrl(environmentId, resource);
41 const uri = mediaVideoPreviewUri(source, asset._tag === "Success" ? asset.url : null);
42 return {
43 uri,
44 ...(resource !== null
45 ? { resolvePlaybackUri: async () => mediaVideoPreviewUri(source, await refreshAssetUrl()) }
46 : {}),
47 unavailable:
48 uri === null &&
49 environmentId !== null &&
50 (connection._tag === "None" || asset._tag === "Failure"),
51 error: null,
52 actionsSource: source.actionsSource,
53 };
55​
56function useLocalPlayback(source: LocalVideoPreviewSource): PlaybackState {
57 const { attachment } = source;
58 const [uri, setUri] = useState<string | null>(null);
59 const [error, setError] = useState<string | null>(null);
60 // Only a different file needs a new lease; a metadata update on the same
61 // draft must not dispose the file Android is still playing.
62 const attachmentRef = useRef(attachment);
63 attachmentRef.current = attachment;
64 const { id: attachmentId, fileUri } = attachment;
65 useEffect(() => {
66 setUri(null);
67 setError(null);
68 const controller = new AbortController();
69 const loading = loadLocalAttachmentPreview(attachmentRef.current, controller.signal);
70 void loading.then(
71 (file) => {
72 if (file === null) return;
73 if (controller.signal.aborted) file.dispose();
74 else setUri(file.uri);
75 },
76 (cause: unknown) => {
77 if (!controller.signal.aborted) {
78 setError(cause instanceof Error ? cause.message : "Could not load this video.");
79 }
80 },
81 );
82 return () => {
83 controller.abort();
84 void loading.then(
85 (file) => file?.dispose(),
86 () => undefined,
87 );
88 };
89 }, [attachmentId, fileUri]);
90 const mimeType = videoMimeType(attachment) ?? attachment.mimeType;
91 return {
92 uri,
93 unavailable: error !== null,
94 error,
95 actionsSource: uri === null ? undefined : { name: attachment.name, mimeType, uri },
96 };
98​
99function MediaPreviewModal(props: {
100 readonly source: MediaVideoPreviewSource;
101 readonly onRequestClose: () => void;
102}) {
103 return (
104 <OpenVideoPreviewModal
105 name={props.source.name}
106 thumbnailKey={mediaVideoThumbnailKey(props.source)}
107 playback={useMediaPlayback(props.source)}
108 onRequestClose={props.onRequestClose}
109 />
110 );
112​
113function LocalPreviewModal(props: {
114 readonly source: LocalVideoPreviewSource;
115 readonly onRequestClose: () => void;
116}) {
117 return (
118 <OpenVideoPreviewModal
119 name={props.source.attachment.name}
120 thumbnailKey={`local:${props.source.attachment.id}`}
121 playback={useLocalPlayback(props.source)}
122 onRequestClose={props.onRequestClose}
123 />
124 );
126​
127function OpenVideoPreviewModal(props: {
128 readonly name: string;
129 readonly thumbnailKey: string;
130 readonly playback: PlaybackState;
131 readonly onRequestClose: () => void;
132}) {
133 const { playback } = props;
134 const insets = useSafeAreaInsets();
135 const mediaActions = useMediaActions(playback.actionsSource, props.onRequestClose);
136​
137 useEffect(() => Keyboard.dismiss(), []);
138 return (
139 <Modal
140 visible
141 animationType="fade"
142 presentationStyle="fullScreen"
143 onRequestClose={props.onRequestClose}
144 statusBarTranslucent
145 navigationBarTranslucent
146 >
147 <View
148 className="flex-1 bg-black"
149 style={{ paddingTop: insets.top, paddingBottom: insets.bottom }}
150 >
151 <View className="min-h-14 flex-row items-center gap-3 pl-4 pr-2">
152 <AppText className="flex-1 font-t3-medium text-base text-white" numberOfLines={2}>
153 {props.name}
154 </AppText>
155 <MediaActionsMenu media={mediaActions} inModal />
156 <Pressable
157 accessibilityRole="button"
158 accessibilityLabel="Close video"
159 onPress={props.onRequestClose}
160 className="size-12 items-center justify-center"
161 >
162 <SymbolView name="xmark" size={20} tintColor="#ffffff" type="monochrome" />
163 </Pressable>
164 </View>
165 <MediaSourceCaption source={mediaActions.title} />
166 {playback.uri === null && !playback.unavailable ? (
167 <View className="flex-1 items-center justify-center gap-3 px-6">
168 <ActivityIndicator color="#ffffff" />
169 <AppText className="text-sm text-white/80">Loading video...</AppText>
170 </View>
171 ) : (
172 <MediaVideoPlayer
173 uri={playback.uri}
174 resolvePlaybackUri={playback.resolvePlaybackUri}
175 name={props.name}
176 thumbnailKey={props.thumbnailKey}
177 unavailable={playback.unavailable}
178 paused={mediaActions.sharing}
179 expanded
180 autoPlay
181 />
182 )}
183 {playback.error ? (
184 <AppText accessibilityRole="alert" className="px-4 pb-3 text-sm text-white/80">
185 {playback.error}
186 </AppText>
187 ) : null}
188 <Pressable
189 accessibilityRole="button"
190 accessibilityLabel="Save or share video"
191 disabled={playback.uri === null || mediaActions.sharing}
192 onPress={mediaActions.share}
193 className="mx-4 my-3 min-h-12 items-center justify-center rounded-xl bg-white/15 px-4"
194 >
195 <AppText className="font-t3-medium text-base text-white">
196 {mediaActions.sharing ? "Opening share sheet..." : "Save or share video"}
197 </AppText>
198 </Pressable>
199 </View>
200 </Modal>
201 );
203​
204export function VideoPreviewModal(props: {
205 readonly source: VideoPreviewSource | null;
206 readonly onRequestClose: () => void;
207}) {
208 const isFocused = useIsFocused();
209 const hasSource = props.source !== null;
210 useEffect(() => {
211 if (!isFocused && hasSource) props.onRequestClose();
212 }, [isFocused, hasSource, props.onRequestClose]);
213 const { source } = props;
214 if (source === null || !isFocused) return null;
215 return source.type === "local" ? (
216 <LocalPreviewModal
217 key={`local:${source.attachment.id}:${source.attachment.fileUri}`}
218 source={source}
219 onRequestClose={props.onRequestClose}
220 />
221 ) : (
222 <MediaPreviewModal
223 key={mediaVideoThumbnailKey(source)}
224 source={source}
225 onRequestClose={props.onRequestClose}
226 />
227 );