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

AttachmentFileScreen.tsx

440 lines16.6 KB

1/* oxlint-disable react/no-array-index-key -- Captured table rows and columns have stable positions and may contain identical values. */
2import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
3import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
4import type { MenuAction } from "@react-native-menu/menu";
5import { EnvironmentId } from "@t3tools/contracts";
6import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
7import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8import { ActivityIndicator, Alert, Platform, ScrollView, View } from "react-native";
9​
10import { AndroidHeaderIconButton, AndroidScreenHeader } from "../../components/AndroidScreenHeader";
11import { AppText as Text } from "../../components/AppText";
12import { AudioFilePreview } from "../../components/AudioFilePreview";
13import { ControlPillMenu } from "../../components/ControlPill";
14import { EmptyState } from "../../components/EmptyState";
15import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
16import { useAttachmentDocument } from "../../lib/attachmentDocument";
17import { nativeViewerErrorMessage } from "../../lib/attachmentDownload";
18import { isFileBackedComposerAttachment } from "../../lib/composerImages";
19import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
20import { useUniwindTheme } from "../../lib/useUniwindTheme";
21import { removeComposerDraftAttachment, useComposerDraft } from "../../state/use-composer-drafts";
22import { FileMarkdownPreview } from "./FileMarkdownPreview";
23import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
24import { SourceFileSurface } from "./SourceFileSurface";
25import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
26​
27/**
28 * Both the thread stack and the new-task sheet stack register this screen, so a chip in a
29 * sent message and a chip in a draft open the same view a workspace file does.
30 */
31export type AttachmentFileRouteParams = {
32 readonly environmentId?: string;
33 readonly threadId?: string;
34 readonly attachmentId: string;
35 readonly name: string;
36 readonly mimeType: string;
37 readonly sizeBytes: string;
38 /** Present for a draft attachment, which may still live only on this device. */
39 readonly draftKey?: string;
40};
41​
42type AttachmentFileScreenProps = StaticScreenProps<AttachmentFileRouteParams>;
43​
44/** Kinds this screen cannot render itself; the platform viewer is the primary presentation. */
45function nativeViewerKind(kind: ReturnType<typeof useAttachmentDocument>["kind"]) {
46 if (kind === "image") return "image" as const;
47 if (kind === "pdf") return "pdf" as const;
48 if (kind === "video" || kind === "unsupported") return "document" as const;
49 return null;
51​
52function AttachmentDocumentBody(props: {
53 readonly document: ReturnType<typeof useAttachmentDocument>;
54 readonly name: string;
55 readonly environmentId: EnvironmentId | null;
56 readonly nativeViewer: "pending" | "open" | "unavailable" | null;
57 readonly nativeError: string | null;
58 readonly onOpenNative: () => void;
59}) {
60 const { document } = props;
61 if (document.error) {
62 return (
63 <View className="flex-1 items-center justify-center bg-sheet px-6">
64 <EmptyState
65 title="File unavailable"
66 detail={document.error}
67 actionLabel="Try again"
68 onAction={document.retry}
69 />
70 </View>
71 );
72 }
73 if (props.nativeViewer !== null && props.nativeViewer !== "unavailable") {
74 return (
75 <View className="flex-1 items-center justify-center gap-3 bg-sheet px-6">
76 <ActivityIndicator />
77 <Text className="text-center text-sm text-foreground-muted">Opening in file viewer...</Text>
78 </View>
79 );
80 }
81 if (!document.uri || (document.needsText && !document.content)) {
82 return (
83 <View className="flex-1 items-center justify-center gap-3 bg-sheet px-6">
84 <ActivityIndicator />
85 <Text className="text-center text-sm text-foreground-muted">Loading file...</Text>
86 </View>
87 );
88 }
89 if (document.needsText && document.content) {
90 const { content, table } = document;
91 return (
92 <View className="flex-1 bg-sheet">
93 {content.truncated ? (
94 <View className="border-b border-warning-border bg-warning px-4 py-2">
95 <Text className="text-2xs font-t3-bold uppercase text-warning-foreground">
96 Partial file
97 </Text>
98 <Text className="text-xs leading-snug text-warning-foreground">
99 Preview limited to the first 1 MB. Save or share the file to read it in full.
100 </Text>
101 </View>
102 ) : null}
103 {table && document.activeMode === "table" ? (
104 <ScrollView className="flex-1">
105 {table.truncated ? (
106 <View className="border-b border-warning-border bg-warning px-4 py-2">
107 <Text className="text-xs leading-snug text-warning-foreground">
108 Table limited to the first 100 rows and 30 columns. Source shows the rest.
109 </Text>
110 </View>
111 ) : null}
112 <ScrollView horizontal>
113 <View>
114 {table.rows.map((row, rowIndex) => (
115 <View
116 key={rowIndex}
117 className={rowIndex === 0 ? "flex-row bg-subtle" : "flex-row"}
118 >
119 {row.map((cell, columnIndex) => (
120 <View
121 key={columnIndex}
122 className="w-48 border-r border-b border-border px-3 py-2"
123 >
124 <Text
125 selectable
126 className={
127 rowIndex === 0
128 ? "text-sm font-t3-semibold text-foreground"
129 : "text-sm text-foreground"
130 }
131 >
132 {cell}
133 </Text>
134 </View>
135 ))}
136 </View>
137 ))}
138 </View>
139 </ScrollView>
140 </ScrollView>
141 ) : document.activeMode === "markdown" && props.environmentId ? (
142 <FileMarkdownPreview
143 cwd=""
144 relativePath=""
145 environmentId={props.environmentId}
146 threadId={null}
147 markdown={content.text}
148 captured
149 />
150 ) : (
151 <SourceFileSurface contents={content.text} path={props.name} selectable />
152 )}
153 </View>
154 );
155 }
156 if (document.kind === "audio") {
157 return <AudioFilePreview key={document.revision} uri={document.uri} onRetry={document.retry} />;
158 }
159 if (document.kind === "html") {
160 return <WorkspaceFileWebPreview uri={document.uri} />;
161 }
162 return (
163 <View className="flex-1 items-center justify-center bg-sheet px-6">
164 <EmptyState
165 title="No preview for this file"
166 detail={
167 props.nativeError ??
168 "No app on this device can show this format. Save or share it to open it elsewhere."
169 }
170 actionLabel="Try again"
171 onAction={props.onOpenNative}
172 />
173 </View>
174 );
176​
177export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
178 const navigation = useNavigation();
179 const { appearance, setCodeWordBreak } = useAppearancePreferences();
180 const iconColor = useUniwindTheme()["--color-icon"];
181 const isAndroid = Platform.OS === "android";
182 const params = props.route.params;
183 const environmentId = params.environmentId ? EnvironmentId.make(params.environmentId) : null;
184 const sizeBytes = Number.parseInt(params.sizeBytes, 10) || 0;
185 const draftKey = params.draftKey ?? null;
186 const draft = useComposerDraft(draftKey);
187 const draftAttachment = draftKey
188 ? draft.attachments.find((entry) => entry.id === params.attachmentId)
189 : undefined;
190 const localAttachment =
191 draftAttachment && isFileBackedComposerAttachment(draftAttachment) ? draftAttachment : null;
192 const document = useAttachmentDocument({
193 name: params.name,
194 mimeType: params.mimeType,
195 sizeBytes,
196 attachmentId: params.attachmentId,
197 environmentId,
198 attachment: localAttachment,
199 });
200 const [nativeOpen, setNativeOpen] = useState(false);
201 // A format we cannot render goes straight to the system viewer; this screen is only the
202 // launch pad and, when no viewer can show it, the honest fallback.
203 const nativeKind = nativeViewerKind(document.kind);
204 const [nativeViewer, setNativeViewer] = useState<"pending" | "open" | "unavailable" | null>(
205 nativeKind ? "pending" : null,
206 );
207 const [nativeError, setNativeError] = useState<string | null>(null);
208 const pendingNativeError = useRef<string | null>(null);
209 const handleBack = useCallback(() => {
210 if (navigation.canGoBack()) navigation.goBack();
211 }, [navigation]);
212 const { uri, resource } = document;
213 useEffect(() => {
214 if (nativeViewer !== "pending" || !uri) return;
215 // oxlint-disable-next-line react/set-state-in-effect -- Presenting the viewer waits on the resolved file.
216 setNativeViewer("open");
217 setNativeOpen(true);
218 }, [nativeViewer, uri]);
219 // The viewer mints its own fresh URL from the resource, so a link that expired while this
220 // screen sat in the background is never handed to Quick Look or ACTION_VIEW.
221 const nativeSource = useMemo<FilePreviewSource | null>(() => {
222 const kind = nativeKind ?? "document";
223 const base = { kind, name: params.name, mimeType: params.mimeType };
224 if (localAttachment) return { ...base, attachment: localAttachment };
225 if (environmentId) return { ...base, environmentId, resource };
226 return uri ? { ...base, uri } : null;
227 }, [environmentId, localAttachment, nativeKind, params.mimeType, params.name, resource, uri]);
228 const handleNativeOpenError = useCallback((error: unknown) => {
229 pendingNativeError.current = nativeViewerErrorMessage(error);
230 }, []);
231 const handleNativeClose = useCallback(() => {
232 setNativeOpen(false);
233 const message = pendingNativeError.current;
234 pendingNativeError.current = null;
235 if (nativeViewer === null) {
236 // A file this screen renders itself: an explicit viewer failure is worth a word.
237 if (message) Alert.alert("Could not open document", message);
238 return;
239 }
240 if (message) {
241 setNativeError(message);
242 setNativeViewer("unavailable");
243 return;
244 }
245 // The viewer was the whole visit: return to the conversation rather than a blank screen.
246 handleBack();
247 }, [handleBack, nativeViewer]);
248 const removeFromDraft = useCallback(() => {
249 if (!draftKey) return;
250 removeComposerDraftAttachment(draftKey, params.attachmentId);
251 handleBack();
252 }, [draftKey, handleBack, params.attachmentId]);
253​
254 const { content, renderedMode, activeMode, setRendered, share, sharing } = document;
255 const menuActions = useMemo(
256 () =>
257 [
258 renderedMode
259 ? ({
260 id: "preview",
261 title: renderedMode === "table" ? "Table" : "Preview",
262 icon: renderedMode === "table" ? "tablecells" : "eye",
263 inline: true,
264 onPress: () => setRendered(true),
265 } as const)
266 : null,
267 renderedMode
268 ? ({
269 id: "source",
270 title: "Source",
271 icon: "doc.text",
272 inline: true,
273 onPress: () => setRendered(false),
274 } as const)
275 : null,
276 content && activeMode === "source"
277 ? ({
278 id: "word-wrap",
279 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
280 icon: "text.alignleft",
281 inline: false,
282 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
283 } as const)
284 : null,
285 content
286 ? ({
287 id: "copy",
288 title: content.truncated ? "Copy preview" : "Copy contents",
289 icon: "doc.on.doc",
290 inline: false,
291 onPress: () => copyTextWithHaptic(content.text),
292 } as const)
293 : null,
294 uri
295 ? ({
296 id: "share",
297 title: sharing ? "Opening share sheet…" : "Save or share",
298 icon: "square.and.arrow.up",
299 inline: false,
300 onPress: () => void share(),
301 } as const)
302 : null,
303 uri
304 ? ({
305 id: "open-viewer",
306 title: "Open in file viewer",
307 icon: "arrow.up.left.and.arrow.down.right",
308 inline: false,
309 onPress: () => {
310 setNativeViewer((current) => (current === null ? null : "open"));
311 setNativeOpen(true);
312 },
313 } as const)
314 : null,
315 draftKey
316 ? ({
317 id: "remove",
318 title: "Remove from draft",
319 icon: "trash",
320 inline: false,
321 destructive: true,
322 onPress: removeFromDraft,
323 } as const)
324 : null,
325 ].filter((action) => action !== null),
326 [
327 appearance.codeWordBreak,
328 setCodeWordBreak,
329 content,
330 draftKey,
331 removeFromDraft,
332 activeMode,
333 renderedMode,
334 setRendered,
335 share,
336 sharing,
337 uri,
338 ],
339 );
340 const selectedAction = activeMode === "source" ? "source" : "preview";
341 const androidMenuActions = useMemo<MenuAction[]>(
342 () =>
343 menuActions.map((action) => ({
344 id: action.id,
345 title: action.title,
346 image: action.icon,
347 state: action.inline ? (action.id === selectedAction ? "on" : "off") : undefined,
348 ...("destructive" in action ? { attributes: { destructive: true } } : {}),
349 })),
350 [selectedAction, menuActions],
351 );
352 const handleAndroidMenuAction = useCallback(
353 (event: { nativeEvent: { event: string } }) => {
354 menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();
355 },
356 [menuActions],
357 );
358 const subtitle = `${draftKey ? "Draft attachment" : "Attachment"} · ${formatAttachmentSize(sizeBytes)}`;
359​
360 return (
361 <View className="flex-1 bg-sheet">
362 <NativeStackScreenOptions
363 options={{
364 headerShown: !isAndroid,
365 headerTintColor: iconColor,
366 headerTitle: params.name,
367 title: params.name,
368 unstable_headerSubtitle: Platform.OS === "ios" ? subtitle : undefined,
369 }}
370 />
371 {isAndroid ? (
372 <AndroidScreenHeader
373 title={params.name}
374 subtitle={subtitle}
375 onBack={handleBack}
376 trailing={
377 <ControlPillMenu
378 actions={androidMenuActions}
379 isAnchoredToRight
380 title="File actions"
381 onPressAction={handleAndroidMenuAction}
382 >
383 <AndroidHeaderIconButton accessibilityLabel="File actions" icon="ellipsis" />
384 </ControlPillMenu>
385 }
386 />
387 ) : null}
388 <NativeHeaderToolbar placement="right">
389 <NativeHeaderToolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
390 {renderedMode ? (
391 <NativeHeaderToolbar.Menu inline>
392 {menuActions
393 .filter(({ inline }) => inline)
394 .map((action) => (
395 <NativeHeaderToolbar.MenuAction
396 key={action.id}
397 icon={action.icon}
398 isOn={action.id === selectedAction}
399 onPress={action.onPress}
400 >
401 {action.title}
402 </NativeHeaderToolbar.MenuAction>
403 ))}
404 </NativeHeaderToolbar.Menu>
405 ) : null}
406 {menuActions
407 .filter(({ inline }) => !inline)
408 .map((action) => (
409 <NativeHeaderToolbar.MenuAction
410 key={action.id}
411 icon={action.icon}
412 destructive={"destructive" in action}
413 onPress={action.onPress}
414 >
415 {action.title}
416 </NativeHeaderToolbar.MenuAction>
417 ))}
418 </NativeHeaderToolbar.Menu>
419 </NativeHeaderToolbar>
420 <AttachmentDocumentBody
421 document={document}
422 name={params.name}
423 environmentId={environmentId}
424 nativeViewer={nativeViewer}
425 nativeError={nativeError}
426 onOpenNative={() => {
427 setNativeViewer((current) => (current === null ? null : "open"));
428 setNativeOpen(true);
429 }}
430 />
431 {nativeOpen && nativeSource ? (
432 <FilePreviewModal
433 source={nativeSource}
434 onRequestClose={handleNativeClose}
435 onOpenError={handleNativeOpenError}
436 />
437 ) : null}
438 </View>
439 );