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

ThreadInlineFilePreview.tsx

254 lines9.1 KB

1import { useIsFocused } from "@react-navigation/native";
2import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
3import { useAudioPlayerStatus } from "expo-audio";
4import { useCallback, useContext, useEffect, useRef, useState } from "react";
5import { AppState, Pressable, View } from "react-native";
6import type { FilePreviewSource } from "../../components/FilePreviewModal";
7import { filePreviewKey } from "../../lib/filePreviewGallery";
8import { PierreEntryIcon } from "../../components/PierreEntryIcon";
9import { AppText as Text } from "../../components/ui/AppText";
10import { SymbolView } from "../../components/ui/AppSymbol";
11import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../../lib/videoAudioSession";
12import { useRefreshAssetUrl } from "../../state/assets";
13import { ThreadMediaVisibleContext } from "./ThreadMarkdownVideo";
14import {
15 acquireAudioSession,
16 activateAudioSession,
17 isAudioSessionOwner,
18 pauseAudioPlayer,
19 releaseAudioSession,
20} from "../../lib/audioSession";
21import { usePlaybackAudioPlayer } from "../voice-input/usePlaybackAudioPlayer";
22​
23type PreviewProps = {
24 readonly source: FilePreviewSource;
25 readonly sizeBytes?: number;
26 readonly onOpen: () => void;
27 readonly onPlaybackStart?: () => void;
28 readonly onLongPress?: () => void;
29};
30​
31function FileCardHeader(props: PreviewProps) {
32 return (
33 <Pressable
34 accessibilityRole="button"
35 accessibilityLabel={`Open ${props.source.name}`}
36 onPress={props.onOpen}
37 onLongPress={props.onLongPress}
38 className="h-[72px] flex-row items-center gap-3 p-3 active:bg-subtle"
39 >
40 <View className="h-12 w-10 shrink-0 items-center justify-center rounded-lg bg-subtle">
41 <PierreEntryIcon path={props.source.name ?? "file"} kind="file" size={26} />
42 </View>
43 <View className="min-w-0 flex-1 gap-1">
44 <Text className="text-sm font-t3-medium text-foreground" numberOfLines={1}>
45 {props.source.name}
46 </Text>
47 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
48 Audio
49 {props.sizeBytes !== undefined ? ` · ${formatAttachmentSize(props.sizeBytes)}` : ""}
50 </Text>
51 </View>
52 <SymbolView name="chevron.right" size={12} tintColorClassName="accent-foreground-muted" />
53 </Pressable>
54 );
56​
57function timestamp(seconds: number) {
58 const value = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0;
59 return `${Math.floor(value / 60)}:${String(value % 60).padStart(2, "0")}`;
61​
62function InlineAudio(props: PreviewProps & { readonly resolveUri: () => Promise<string | null> }) {
63 // An empty source keeps native buffering off until the user explicitly plays.
64 const player = usePlaybackAudioPlayer(null);
65 const status = useAudioPlayerStatus(player);
66 const [loading, setLoading] = useState(false);
67 const [error, setError] = useState(false);
68 const active = useRef(true);
69 const requestGeneration = useRef(0);
70 const playRequested = useRef(false);
71 const audioToken = useRef<ReturnType<typeof acquireAudioSession> | null>(null);
72 const [playbackRequested, setPlaybackRequested] = useState(false);
73 const requestPlayback = useCallback((requested: boolean) => {
74 playRequested.current = requested;
75 setPlaybackRequested(requested);
76 if (!requested) {
77 requestGeneration.current += 1;
78 setLoading(false);
79 if (audioToken.current) {
80 void releaseAudioSession(audioToken.current).catch(() => {});
81 audioToken.current = null;
82 }
83 }
84 }, []);
85 useMediaAudioSessionHold(status.playing);
86 const fullscreenVideoOpen = useFullscreenVideoOpen();
87 useEffect(() => {
88 if (fullscreenVideoOpen || status.didJustFinish || status.error) {
89 // oxlint-disable-next-line react/set-state-in-effect -- Native completion and fullscreen takeover invalidate the pending playback request.
90 requestPlayback(false);
91 }
92 if (fullscreenVideoOpen) pauseAudioPlayer(player);
93 }, [fullscreenVideoOpen, status.didJustFinish, status.error, player, requestPlayback]);
94 useEffect(() => {
95 active.current = true;
96 const subscription = AppState.addEventListener("change", (state) => {
97 if (state !== "active") {
98 requestPlayback(false);
99 pauseAudioPlayer(player);
100 }
101 });
102 return () => {
103 active.current = false;
104 playRequested.current = false;
105 requestGeneration.current += 1;
106 if (audioToken.current) {
107 void releaseAudioSession(audioToken.current).catch(() => {});
108 audioToken.current = null;
109 }
110 subscription.remove();
111 };
112 }, [player, requestPlayback]);
113 const toggle = () => {
114 if (status.playing || playRequested.current) {
115 requestPlayback(false);
116 return pauseAudioPlayer(player);
117 }
118 const token = acquireAudioSession(
119 "playback",
120 () => {
121 requestPlayback(false);
122 pauseAudioPlayer(player);
123 },
124 () => {
125 try {
126 pauseAudioPlayer(player);
127 } catch {}
128 },
129 );
130 if (!isAudioSessionOwner(token)) return;
131 props.onPlaybackStart?.();
132 audioToken.current = token;
133 requestPlayback(true);
134 const generation = ++requestGeneration.current;
135 const isCurrentRequest = () =>
136 active.current &&
137 playRequested.current &&
138 requestGeneration.current === generation &&
139 isAudioSessionOwner(token);
140 setLoading(true);
141 setError(false);
142 void Promise.resolve()
143 .then(async () => {
144 if (!isCurrentRequest()) return;
145 if (!status.isLoaded || status.error) {
146 const uri = await props.resolveUri();
147 if (!isCurrentRequest() || AppState.currentState !== "active") return;
148 if (!uri) {
149 requestPlayback(false);
150 setError(true);
151 return;
152 }
153 player.replace({ uri });
154 } else if (status.didJustFinish || status.currentTime >= status.duration) {
155 await player.seekTo(0);
156 }
157 if (!isCurrentRequest() || AppState.currentState !== "active") return;
158 await activateAudioSession(token);
159 if (isCurrentRequest() && AppState.currentState === "active") player.play();
160 })
161 .catch(() => {
162 if (isCurrentRequest()) {
163 requestPlayback(false);
164 setError(true);
165 }
166 })
167 .finally(() => {
168 if (isCurrentRequest()) setLoading(false);
169 });
170 };
171 const progress =
172 status.duration > 0 ? Math.min(1, Math.max(0, status.currentTime / status.duration)) : 0;
173 const playing = playbackRequested || status.playing;
174 const busy = loading || (playbackRequested && status.isBuffering);
175 return (
176 <>
177 <FileCardHeader
178 {...props}
179 onOpen={() => {
180 requestPlayback(false);
181 pauseAudioPlayer(player);
182 props.onOpen();
183 }}
184 />
185 <View className="h-14 flex-row items-center gap-3 px-3 pb-2">
186 <Pressable
187 accessibilityRole="button"
188 accessibilityLabel={
189 playing ? "Pause audio" : error || status.error ? "Retry audio" : "Play audio"
190 }
191 accessibilityState={{ busy }}
192 onPress={toggle}
193 className="h-11 w-11 items-center justify-center rounded-lg bg-subtle"
194 >
195 <SymbolView
196 name={playing ? "pause" : "play"}
197 size={18}
198 tintColorClassName="accent-foreground"
199 />
200 </Pressable>
201 <View className="min-w-0 flex-1 gap-2">
202 <View
203 accessibilityRole="progressbar"
204 accessibilityValue={{ min: 0, max: status.duration || 0, now: status.currentTime }}
205 className="h-1 overflow-hidden rounded-full bg-subtle"
206 >
207 <View className="h-1 bg-foreground-muted" style={{ width: `${progress * 100}%` }} />
208 </View>
209 <Text className="text-xs text-foreground-muted" numberOfLines={1}>
210 {error || status.error
211 ? "Unavailable · tap play to retry"
212 : busy
213 ? "Loading…"
214 : `${timestamp(status.currentTime)} / ${status.isLoaded ? timestamp(status.duration) : "--:--"}`}
215 </Text>
216 </View>
217 </View>
218 </>
219 );
221​
222function VisibleFilePreview(props: PreviewProps) {
223 // Each mounted preview owns its source; feed streaming must not restart a fetch or player.
224 const [source] = useState(props.source);
225 const refresh = useRefreshAssetUrl(
226 "environmentId" in source ? source.environmentId : null,
227 "resource" in source ? source.resource : null,
228 );
229 const resolveUri = useCallback(
230 () => ("uri" in source ? Promise.resolve(source.uri) : refresh()),
231 [source, refresh],
232 );
233 return <InlineAudio {...props} resolveUri={resolveUri} />;
235​
236export function ThreadInlineFilePreview(props: PreviewProps) {
237 const visible = useContext(ThreadMediaVisibleContext);
238 const focused = useIsFocused();
239 return (
240 <View
241 className="my-1 overflow-hidden rounded-xl border border-border bg-card"
242 style={{ width: 280, maxWidth: "100%" }}
243 >
244 {visible && focused ? (
245 <VisibleFilePreview key={filePreviewKey(props.source)} {...props} />
246 ) : (
247 <>
248 <FileCardHeader {...props} />
249 <View className="h-14" />
250 </>
251 )}
252 </View>
253 );