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

VideoPreviewModal.ios.tsx

134 lines5.1 KB

1import * as Dialog from "./ui/Dialog";
2import { useIsFocused } from "@react-navigation/native";
3import { requireNativeModule } from "expo";
4import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
5import { AsyncResult } from "effect/reactivity";
6import { useEffect, useEffectEvent, useId, useState } from "react";
7import { Keyboard } from "react-native";
8​
9import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
10import { fullscreenVideoClosed, fullscreenVideoOpened } from "../lib/videoAudioSession";
11import { mediaVideoPreviewUri, type VideoPreviewSource } from "../lib/videoPreviewSource";
12import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
13import { usePreparedConnection } from "../state/session";
14​
15export type { VideoPreviewSource } from "../lib/videoPreviewSource";
16​
17const NativeControls = requireNativeModule<{
18 presentVideo(
19 uri: string,
20 title: string,
21 sourceIdentifier: string,
22 identifier: string,
23 ): Promise<void>;
24 dismissVideo(identifier: string): Promise<void>;
25}>("T3NativeControls");
26​
27function NativeVideoPreview(props: {
28 readonly source: VideoPreviewSource;
29 readonly onRequestClose: () => void;
30}) {
31 const { source } = props;
32 const localAttachment = source.type === "local" ? source.attachment : null;
33 const identifier = useId();
34 const onRequestClose = useEffectEvent(props.onRequestClose);
35 const environmentId =
36 source.type === "media" && "environmentId" in source ? source.environmentId : null;
37 const resource = source.type === "media" && "resource" in source ? source.resource : null;
38 const preparedConnection = usePreparedConnection(environmentId);
39 const assetUrl = useAssetUrlState(environmentId, resource);
40 const refreshAssetUrl = useEffectEvent(useRefreshAssetUrl(environmentId, resource));
41 const name = source.type === "media" ? source.name : source.attachment.name;
42 // The first minted URL is kept so a background refresh does not restart playback.
43 const resolvedUrl =
44 source.type === "media"
45 ? mediaVideoPreviewUri(source, assetUrl._tag === "Success" ? assetUrl.url : null)
46 : null;
47 const [playbackUrl, setPlaybackUrl] = useState<string | null>(resolvedUrl);
48 const loadError =
49 resource !== null && playbackUrl === null
50 ? preparedConnection._tag === "None"
51 ? "Reconnect to this environment and open the video again."
52 : assetUrl._tag === "Failure"
53 ? "Could not load this video. Check the connection and try again."
54 : null
55 : null;
56​
57 useEffect(() => Keyboard.dismiss(), []);
58 useEffect(() => {
59 fullscreenVideoOpened();
60 return () => fullscreenVideoClosed();
61 }, []);
62 useEffect(() => {
63 if (playbackUrl === null && resolvedUrl !== null) setPlaybackUrl(resolvedUrl);
64 }, [playbackUrl, resolvedUrl]);
65 useEffect(() => {
66 if (!loadError) return;
67 Dialog.alert("Could not open video", loadError);
68 onRequestClose();
69 }, [loadError]);
70​
71 useEffect(() => {
72 if (localAttachment === null && playbackUrl === null) return;
73 const controller = new AbortController();
74 let ready = false;
75 void (async () => {
76 const file =
77 localAttachment !== null
78 ? await loadLocalAttachmentPreview(localAttachment, controller.signal)
79 : null;
80 if (localAttachment !== null && !file) return;
81 if (controller.signal.aborted) {
82 file?.dispose();
83 return;
84 }
85 ready = true;
86 const presented = await settlePromise(() =>
87 NativeControls.presentVideo(
88 file?.uri ?? playbackUrl!,
89 name,
90 source.sourceIdentifier ?? "",
91 identifier,
92 ),
93 );
94 // Native completion follows dismissal, so local playback keeps its file lease.
95 file?.dispose();
96 if (AsyncResult.isFailure(presented)) throw squashAtomCommandFailure(presented);
97 if (!controller.signal.aborted) onRequestClose();
98 })().catch((error: unknown) => {
99 if (controller.signal.aborted) return;
100 // AVKit gives no retry, so re-mint now; the cached URL may simply have expired.
101 if (ready) void refreshAssetUrl();
102 Dialog.alert(
103 "Could not open video",
104 ready
105 ? "This video couldn't be loaded or played. Check the connection, or touch and hold the video to save or share the original."
106 : error instanceof Error
107 ? error.message
108 : "Could not load this video.",
109 );
110 onRequestClose();
111 });
112 return () => {
113 controller.abort();
114 void NativeControls.dismissVideo(identifier).catch(() => undefined);
115 };
116 }, [localAttachment, name, source.sourceIdentifier, playbackUrl, identifier]);
117​
118 return null;
120​
121export function VideoPreviewModal(props: {
122 readonly source: VideoPreviewSource | null;
123 readonly onRequestClose: () => void;
124}) {
125 const isFocused = useIsFocused();
126 const hasSource = props.source !== null;
127 const onRequestClose = useEffectEvent(props.onRequestClose);
128 useEffect(() => {
129 if (!isFocused && hasSource) onRequestClose();
130 }, [isFocused, hasSource]);
131​
132 if (!props.source || !isFocused) return null;
133 return <NativeVideoPreview source={props.source} onRequestClose={props.onRequestClose} />;