Open History to see the last commit
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";
14import {
15 acquireAudioSession,
16 activateAudioSession,
17 isAudioSessionOwner,
18 releaseAudioSession,
19} from "../lib/audioSession";
20
21export type { VideoPreviewSource } from "../lib/videoPreviewSource";
22
23const NativeControls = requireNativeModule<{
24 presentVideo(
25 uri: string,
26 title: string,
27 sourceIdentifier: string,
28 identifier: string,
29 ): Promise<void>;
30 dismissVideo(identifier: string): Promise<void>;
31 addListener(
32 event: "videoPlaybackChange",
33 listener: (event: { identifier: string; isPlaying: boolean }) => void,
34 ): { remove(): void };
35}>("T3NativeControls");
36
37function NativeVideoPreview(props: {
38 readonly source: VideoPreviewSource;
39 readonly onRequestClose: () => void;
40}) {
41 const { source } = props;
42 const localAttachment = source.type === "local" ? source.attachment : null;
43 const identifier = useId();
44 const onRequestClose = useEffectEvent(props.onRequestClose);
45 const environmentId =
46 source.type === "media" && "environmentId" in source ? source.environmentId : null;
47 const resource = source.type === "media" && "resource" in source ? source.resource : null;
48 const preparedConnection = usePreparedConnection(environmentId);
49 const assetUrl = useAssetUrlState(environmentId, resource);
50 const refreshAssetUrl = useEffectEvent(useRefreshAssetUrl(environmentId, resource));
51 const name = source.type === "media" ? source.name : source.attachment.name;
52 // The first minted URL is kept so a background refresh does not restart playback.
53 const resolvedUrl =
54 source.type === "media"
55 ? mediaVideoPreviewUri(source, assetUrl._tag === "Success" ? assetUrl.url : null)
56 : null;
57 const [playbackUrl, setPlaybackUrl] = useState<string | null>(resolvedUrl);
58 const loadError =
59 resource !== null && playbackUrl === null
60 ? preparedConnection._tag === "None"
61 ? "Reconnect to this environment and open the video again."
62 : assetUrl._tag === "Failure"
63 ? "Could not load this video. Check the connection and try again."
64 : null
65 : null;
66
67 useEffect(() => Keyboard.dismiss(), []);
68 useEffect(() => {
69 fullscreenVideoOpened();
70 return () => fullscreenVideoClosed();
71 }, []);
72 useEffect(() => {
73 // oxlint-disable-next-line react/set-state-in-effect -- The native player latches the first resolved URL to keep its playback session.
74 if (playbackUrl === null && resolvedUrl !== null) setPlaybackUrl(resolvedUrl);
75 }, [playbackUrl, resolvedUrl]);
76 useEffect(() => {
77 if (!loadError) return;
78 Dialog.alert("Could not open video", loadError);
79 onRequestClose();
80 }, [loadError]);
81
82 useEffect(() => {
83 if (localAttachment === null && playbackUrl === null) return;
84 const controller = new AbortController();
85 let token: ReturnType<typeof acquireAudioSession> | null = null;
86 const release = () => {
87 if (token) void releaseAudioSession(token).catch(() => {});
88 token = null;
89 };
90 const acquire = () => {
91 const next = acquireAudioSession("playback", () => {
92 release();
93 void NativeControls.dismissVideo(identifier).catch(() => {});
94 });
95 if (!isAudioSessionOwner(next)) {
96 void NativeControls.dismissVideo(identifier).catch(() => {});
97 return null;
98 }
99 token = next;
100 return next;
101 };
102 const subscription = NativeControls.addListener("videoPlaybackChange", (event) => {
103 if (event.identifier !== identifier || controller.signal.aborted) return;
104 if (event.isPlaying) {
105 if (!token) acquire();
106 } else release();
107 });
108 let ready = false;
109 void (async () => {
110 const file =
111 localAttachment !== null
112 ? await loadLocalAttachmentPreview(localAttachment, controller.signal)
113 : null;
114 if (localAttachment !== null && !file) return;
115 if (controller.signal.aborted) {
116 file?.dispose();
117 return;
118 }
119 const current = acquire();
120 if (!current || !(await activateAudioSession(current, true)) || controller.signal.aborted) {
121 release();
122 file?.dispose();
123 if (!controller.signal.aborted) onRequestClose();
124 return;
125 }
126 ready = true;
127 const presented = await settlePromise(() =>
128 NativeControls.presentVideo(
129 file?.uri ?? playbackUrl!,
130 name,
131 source.sourceIdentifier ?? "",
132 identifier,
133 ),
134 );
135 // Native completion follows dismissal, so local playback keeps its file lease.
136 file?.dispose();
137 release();
138 if (AsyncResult.isFailure(presented)) throw squashAtomCommandFailure(presented);
139 if (!controller.signal.aborted) onRequestClose();
140 })().catch((error: unknown) => {
141 release();
142 if (controller.signal.aborted) return;
143 // AVKit gives no retry, so re-mint now; the cached URL may simply have expired.
144 if (ready) void refreshAssetUrl();
145 Dialog.alert(
146 "Could not open video",
147 ready
148 ? "This video couldn't be loaded or played. Check the connection, or touch and hold the video to save or share the original."
149 : error instanceof Error
150 ? error.message
151 : "Could not load this video.",
152 );
153 onRequestClose();
154 });
155 return () => {
156 controller.abort();
157 subscription.remove();
158 release();
159 void NativeControls.dismissVideo(identifier).catch(() => undefined);
160 };
161 }, [localAttachment, name, source.sourceIdentifier, playbackUrl, identifier]);
162
163 return null;
164}
165
166export function VideoPreviewModal(props: {
167 readonly source: VideoPreviewSource | null;
168 readonly onRequestClose: () => void;
169}) {
170 const isFocused = useIsFocused();
171 const hasSource = props.source !== null;
172 const onRequestClose = useEffectEvent(props.onRequestClose);
173 useEffect(() => {
174 if (!isFocused && hasSource) onRequestClose();
175 }, [isFocused, hasSource]);
176
177 if (!props.source || !isFocused) return null;
178 return <NativeVideoPreview source={props.source} onRequestClose={props.onRequestClose} />;
179}