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