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

AttachmentFileScreen.tsx

370 lines13.1 KB

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 { useEffect, 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;
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 );
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 useEffect(() => {
169 if (nativeViewer !== "pending" || !uri) return;
170 // oxlint-disable-next-line react/set-state-in-effect -- Presenting the viewer waits on the resolved file.
171 setNativeViewer("open");
172 setNativeOpen(true);
173 }, [nativeViewer, uri]);
174 // Mint a fresh URL: cached URLs may expire in the background before Quick Look or ACTION_VIEW opens.
175 const nativeSource = ((): FilePreviewSource | null => {
176 const kind = nativeKind ?? "document";
177 const base = { kind, name: params.name, mimeType: params.mimeType };
178 if (localAttachment) return { ...base, attachment: localAttachment };
179 if (environmentId) return { ...base, environmentId, resource };
180 return uri ? { ...base, uri } : null;
181 })();
182 const handleNativeOpenError = (error: unknown) => {
183 pendingNativeError.current = nativeViewerErrorMessage(error);
184 };
185 const handleNativeClose = () => {
186 setNativeOpen(false);
187 const message = pendingNativeError.current;
188 pendingNativeError.current = null;
189 if (nativeViewer === null) {
190 if (message) Dialog.alert("Could not open document", message);
191 return;
192 }
193 if (message) {
194 setNativeError(message);
195 setNativeViewer("unavailable");
196 return;
197 }
198 handleBack();
199 };
200 const removeFromDraft = () => {
201 if (!draftKey) return;
202 removeComposerDraftAttachment(draftKey, params.attachmentId);
203 handleBack();
204 };
205​
206 const { content, renderedMode, activeMode, setRendered, share, sharing } = document;
207 const menuActions = [
208 renderedMode
209 ? ({
210 id: "preview",
211 title: renderedMode === "table" ? "Table" : "Preview",
212 icon: renderedMode === "table" ? "tablecells" : "eye",
213 inline: true,
214 onPress: () => setRendered(true),
215 } as const)
216 : null,
217 renderedMode
218 ? ({
219 id: "source",
220 title: "Source",
221 icon: "doc.text",
222 inline: true,
223 onPress: () => setRendered(false),
224 } as const)
225 : null,
226 content && activeMode === "source"
227 ? ({
228 id: "word-wrap",
229 title: appearance.codeWordBreak ? "Disable word wrap" : "Enable word wrap",
230 icon: "text.alignleft",
231 inline: false,
232 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
233 } as const)
234 : null,
235 content
236 ? ({
237 id: "copy",
238 title: content.truncated ? "Copy preview" : "Copy contents",
239 icon: "doc.on.doc",
240 inline: false,
241 onPress: () => copyTextWithHaptic(content.text),
242 } as const)
243 : null,
244 uri
245 ? ({
246 id: "share",
247 title: sharing ? "Opening share sheet…" : "Save or share",
248 icon: "square.and.arrow.up",
249 inline: false,
250 onPress: () => void share(),
251 } as const)
252 : null,
253 uri
254 ? ({
255 id: "open-viewer",
256 title: "Open in file viewer",
257 icon: "arrow.up.left.and.arrow.down.right",
258 inline: false,
259 onPress: () => {
260 setNativeViewer((current) => (current === null ? null : "open"));
261 setNativeOpen(true);
262 },
263 } as const)
264 : null,
265 draftKey
266 ? ({
267 id: "remove",
268 title: "Remove from draft",
269 icon: "trash",
270 inline: false,
271 destructive: true,
272 onPress: removeFromDraft,
273 } as const)
274 : null,
275 ].filter((action) => action !== null);
276 const selectedAction = activeMode === "source" ? "source" : "preview";
277 const androidMenuActions = menuActions.map((action) => ({
278 id: action.id,
279 title: action.title,
280 image: action.icon,
281 state: action.inline ? (action.id === selectedAction ? "on" : "off") : undefined,
282 ...("destructive" in action ? { attributes: { destructive: true } } : {}),
283 })) satisfies MenuAction[];
284 const handleAndroidMenuAction = (event: { nativeEvent: { event: string } }) => {
285 menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();
286 };
287 const subtitle = `${draftKey ? "Draft attachment" : "Attachment"}${sizeBytes > 0 ? ` · ${formatAttachmentSize(sizeBytes)}` : ""}`;
288​
289 return (
290 <View className="flex-1 bg-sheet">
291 <NativeStackScreenOptions
292 options={{
293 headerShown: !isAndroid,
294 headerTintColor: iconColor,
295 headerTitle: params.name,
296 title: params.name,
297 unstable_headerSubtitle: Platform.OS === "ios" ? subtitle : undefined,
298 }}
299 />
300 {isAndroid ? (
301 <AndroidScreenHeader
302 title={params.name}
303 subtitle={subtitle}
304 onBack={handleBack}
305 trailing={
306 <Menu
307 actions={androidMenuActions}
308 isAnchoredToRight
309 title="File actions"
310 onPressAction={handleAndroidMenuAction}
311 >
312 <AndroidHeaderIconButton accessibilityLabel="File actions" icon="ellipsis" />
313 </Menu>
314 }
315 />
316 ) : null}
317 <Toolbar placement="right">
318 <Toolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
319 {renderedMode ? (
320 <Toolbar.Menu inline>
321 {menuActions
322 .filter(({ inline }) => inline)
323 .map((action) => (
324 <Toolbar.MenuAction
325 key={action.id}
326 icon={action.icon}
327 isOn={action.id === selectedAction}
328 onPress={action.onPress}
329 >
330 {action.title}
331 </Toolbar.MenuAction>
332 ))}
333 </Toolbar.Menu>
334 ) : null}
335 {menuActions
336 .filter(({ inline }) => !inline)
337 .map((action) => (
338 <Toolbar.MenuAction
339 key={action.id}
340 icon={action.icon}
341 destructive={"destructive" in action}
342 onPress={action.onPress}
343 >
344 {action.title}
345 </Toolbar.MenuAction>
346 ))}
347 </Toolbar.Menu>
348 </Toolbar>
349 <AttachmentDocumentBody
350 document={document}
351 name={params.name}
352 environmentId={environmentId}
353 htmlRender={params.htmlRender === "1"}
354 nativeViewer={nativeViewer}
355 nativeError={nativeError}
356 onOpenNative={() => {
357 setNativeViewer((current) => (current === null ? null : "open"));
358 setNativeOpen(true);
359 }}
360 />
361 {nativeOpen && nativeSource ? (
362 <FilePreviewModal
363 source={nativeSource}
364 onRequestClose={handleNativeClose}
365 onOpenError={handleNativeOpenError}
366 />
367 ) : null}
368 </View>
369 );