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