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