Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AttachmentFileScreen.tsx

407 lines14.7 KB

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;
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 );
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 // 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 = ((): 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 })();
218 const handleNativeOpenError = (error: unknown) => {
219 pendingNativeError.current = nativeViewerErrorMessage(error);
220 };
221 const handleNativeClose = () => {
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 };
237 const removeFromDraft = () => {
238 if (!draftKey) return;
239 removeComposerDraftAttachment(draftKey, params.attachmentId);
240 handleBack();
241 };
242​
243 const { content, renderedMode, activeMode, setRendered, share, sharing } = document;
244 const menuActions = [
245 renderedMode
246 ? ({
247 id: "preview",
248 title: renderedMode === "table" ? "Table" : "Preview",
249 icon: renderedMode === "table" ? "tablecells" : "eye",
250 inline: true,
251 onPress: () => setRendered(true),
252 } as const)
253 : null,
254 renderedMode
255 ? ({
256 id: "source",
257 title: "Source",
258 icon: "doc.text",
259 inline: true,
260 onPress: () => setRendered(false),
261 } as const)
262 : null,
263 content && activeMode === "source"
264 ? ({
265 id: "word-wrap",
266 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
267 icon: "text.alignleft",
268 inline: false,
269 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
270 } as const)
271 : null,
272 content
273 ? ({
274 id: "copy",
275 title: content.truncated ? "Copy preview" : "Copy contents",
276 icon: "doc.on.doc",
277 inline: false,
278 onPress: () => copyTextWithHaptic(content.text),
279 } as const)
280 : null,
281 uri
282 ? ({
283 id: "share",
284 title: sharing ? "Opening share sheet…" : "Save or share",
285 icon: "square.and.arrow.up",
286 inline: false,
287 onPress: () => void share(),
288 } as const)
289 : null,
290 uri
291 ? ({
292 id: "open-viewer",
293 title: "Open in file viewer",
294 icon: "arrow.up.left.and.arrow.down.right",
295 inline: false,
296 onPress: () => {
297 setNativeViewer((current) => (current === null ? null : "open"));
298 setNativeOpen(true);
299 },
300 } as const)
301 : null,
302 draftKey
303 ? ({
304 id: "remove",
305 title: "Remove from draft",
306 icon: "trash",
307 inline: false,
308 destructive: true,
309 onPress: removeFromDraft,
310 } as const)
311 : null,
312 ].filter((action) => action !== null);
313 const selectedAction = activeMode === "source" ? "source" : "preview";
314 const androidMenuActions = menuActions.map((action) => ({
315 id: action.id,
316 title: action.title,
317 image: action.icon,
318 state: action.inline ? (action.id === selectedAction ? "on" : "off") : undefined,
319 ...("destructive" in action ? { attributes: { destructive: true } } : {}),
320 })) satisfies MenuAction[];
321 const handleAndroidMenuAction = (event: { nativeEvent: { event: string } }) => {
322 menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();
323 };
324 const subtitle = `${draftKey ? "Draft attachment" : "Attachment"}${sizeBytes > 0 ? ` · ${formatAttachmentSize(sizeBytes)}` : ""}`;
325​
326 return (
327 <View className="flex-1 bg-sheet">
328 <NativeStackScreenOptions
329 options={{
330 headerShown: !isAndroid,
331 headerTintColor: iconColor,
332 headerTitle: params.name,
333 title: params.name,
334 unstable_headerSubtitle: Platform.OS === "ios" ? subtitle : undefined,
335 }}
336 />
337 {isAndroid ? (
338 <AndroidScreenHeader
339 title={params.name}
340 subtitle={subtitle}
341 onBack={handleBack}
342 trailing={
343 <Menu
344 actions={androidMenuActions}
345 isAnchoredToRight
346 title="File actions"
347 onPressAction={handleAndroidMenuAction}
348 >
349 <AndroidHeaderIconButton accessibilityLabel="File actions" icon="ellipsis" />
350 </Menu>
351 }
352 />
353 ) : null}
354 <Toolbar placement="right">
355 <Toolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
356 {renderedMode ? (
357 <Toolbar.Menu inline>
358 {menuActions
359 .filter(({ inline }) => inline)
360 .map((action) => (
361 <Toolbar.MenuAction
362 key={action.id}
363 icon={action.icon}
364 isOn={action.id === selectedAction}
365 onPress={action.onPress}
366 >
367 {action.title}
368 </Toolbar.MenuAction>
369 ))}
370 </Toolbar.Menu>
371 ) : null}
372 {menuActions
373 .filter(({ inline }) => !inline)
374 .map((action) => (
375 <Toolbar.MenuAction
376 key={action.id}
377 icon={action.icon}
378 destructive={"destructive" in action}
379 onPress={action.onPress}
380 >
381 {action.title}
382 </Toolbar.MenuAction>
383 ))}
384 </Toolbar.Menu>
385 </Toolbar>
386 <AttachmentDocumentBody
387 document={document}
388 name={params.name}
389 environmentId={environmentId}
390 htmlRender={params.htmlRender === "1"}
391 nativeViewer={nativeViewer}
392 nativeError={nativeError}
393 onOpenNative={() => {
394 setNativeViewer((current) => (current === null ? null : "open"));
395 setNativeOpen(true);
396 }}
397 />
398 {nativeOpen && nativeSource ? (
399 <FilePreviewModal
400 source={nativeSource}
401 onRequestClose={handleNativeClose}
402 onOpenError={handleNativeOpenError}
403 />
404 ) : null}
405 </View>
406 );