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