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