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
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 = useCallback(() => {
200 if (navigation.canGoBack()) navigation.goBack();
201 }, [navigation]);
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 // The viewer mints its own fresh URL from the resource, so a link that expired while this
210 // screen sat in the background is never handed to Quick Look or ACTION_VIEW.
211 const nativeSource = useMemo<FilePreviewSource | null>(() => {
212 const kind = nativeKind ?? "document";
213 const base = { kind, name: params.name, mimeType: params.mimeType };
214 if (localAttachment) return { ...base, attachment: localAttachment };
215 if (environmentId) return { ...base, environmentId, resource };
216 return uri ? { ...base, uri } : null;
217 }, [environmentId, localAttachment, nativeKind, params.mimeType, params.name, resource, uri]);
218 const handleNativeOpenError = useCallback((error: unknown) => {
219 pendingNativeError.current = nativeViewerErrorMessage(error);
220 }, []);
221 const handleNativeClose = useCallback(() => {
222 setNativeOpen(false);
223 const message = pendingNativeError.current;
224 pendingNativeError.current = null;
225 if (nativeViewer === null) {
226 // A file this screen renders itself: an explicit viewer failure is worth a word.
227 if (message) Dialog.alert("Could not open document", message);
228 return;
229 }
230 if (message) {
231 setNativeError(message);
232 setNativeViewer("unavailable");
233 return;
234 }
235 handleBack();
236 }, [handleBack, nativeViewer]);
237 const removeFromDraft = useCallback(() => {
238 if (!draftKey) return;
239 removeComposerDraftAttachment(draftKey, params.attachmentId);
240 handleBack();
241 }, [draftKey, handleBack, params.attachmentId]);
242
243 const { content, renderedMode, activeMode, setRendered, share, sharing } = document;
244 const menuActions = useMemo(
245 () =>
246 [
247 renderedMode
248 ? ({
249 id: "preview",
250 title: renderedMode === "table" ? "Table" : "Preview",
251 icon: renderedMode === "table" ? "tablecells" : "eye",
252 inline: true,
253 onPress: () => setRendered(true),
254 } as const)
255 : null,
256 renderedMode
257 ? ({
258 id: "source",
259 title: "Source",
260 icon: "doc.text",
261 inline: true,
262 onPress: () => setRendered(false),
263 } as const)
264 : null,
265 content && activeMode === "source"
266 ? ({
267 id: "word-wrap",
268 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
269 icon: "text.alignleft",
270 inline: false,
271 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
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 [
316 appearance.codeWordBreak,
317 setCodeWordBreak,
318 content,
319 draftKey,
320 removeFromDraft,
321 activeMode,
322 renderedMode,
323 setRendered,
324 share,
325 sharing,
326 uri,
327 ],
328 );
329 const selectedAction = activeMode === "source" ? "source" : "preview";
330 const androidMenuActions = useMemo<MenuAction[]>(
331 () =>
332 menuActions.map((action) => ({
333 id: action.id,
334 title: action.title,
335 image: action.icon,
336 state: action.inline ? (action.id === selectedAction ? "on" : "off") : undefined,
337 ...("destructive" in action ? { attributes: { destructive: true } } : {}),
338 })),
339 [selectedAction, menuActions],
340 );
341 const handleAndroidMenuAction = useCallback(
342 (event: { nativeEvent: { event: string } }) => {
343 menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();
344 },
345 [menuActions],
346 );
347 const subtitle = `${draftKey ? "Draft attachment" : "Attachment"}${sizeBytes > 0 ? ` · ${formatAttachmentSize(sizeBytes)}` : ""}`;
348
349 return (
350 <View className="flex-1 bg-sheet">
351 <NativeStackScreenOptions
352 options={{
353 headerShown: !isAndroid,
354 headerTintColor: iconColor,
355 headerTitle: params.name,
356 title: params.name,
357 unstable_headerSubtitle: Platform.OS === "ios" ? subtitle : undefined,
358 }}
359 />
360 {isAndroid ? (
361 <AndroidScreenHeader
362 title={params.name}
363 subtitle={subtitle}
364 onBack={handleBack}
365 trailing={
366 <Menu
367 actions={androidMenuActions}
368 isAnchoredToRight
369 title="File actions"
370 onPressAction={handleAndroidMenuAction}
371 >
372 <AndroidHeaderIconButton accessibilityLabel="File actions" icon="ellipsis" />
373 </Menu>
374 }
375 />
376 ) : null}
377 <Toolbar placement="right">
378 <Toolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
379 {renderedMode ? (
380 <Toolbar.Menu inline>
381 {menuActions
382 .filter(({ inline }) => inline)
383 .map((action) => (
384 <Toolbar.MenuAction
385 key={action.id}
386 icon={action.icon}
387 isOn={action.id === selectedAction}
388 onPress={action.onPress}
389 >
390 {action.title}
391 </Toolbar.MenuAction>
392 ))}
393 </Toolbar.Menu>
394 ) : null}
395 {menuActions
396 .filter(({ inline }) => !inline)
397 .map((action) => (
398 <Toolbar.MenuAction
399 key={action.id}
400 icon={action.icon}
401 destructive={"destructive" in action}
402 onPress={action.onPress}
403 >
404 {action.title}
405 </Toolbar.MenuAction>
406 ))}
407 </Toolbar.Menu>
408 </Toolbar>
409 <AttachmentDocumentBody
410 document={document}
411 name={params.name}
412 environmentId={environmentId}
413 htmlRender={params.htmlRender === "1"}
414 nativeViewer={nativeViewer}
415 nativeError={nativeError}
416 onOpenNative={() => {
417 setNativeViewer((current) => (current === null ? null : "open"));
418 setNativeOpen(true);
419 }}
420 />
421 {nativeOpen && nativeSource ? (
422 <FilePreviewModal
423 source={nativeSource}
424 onRequestClose={handleNativeClose}
425 onOpenError={handleNativeOpenError}
426 />
427 ) : null}
428 </View>
429 );
430}