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

AttachmentFileScreen.tsx

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