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