Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
3import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4import {
5 clampFileAttachmentUploadBytes,
6 formatAttachmentSize,
7} from "@t3tools/client-runtime/state/attachments";
8import { msg, useGT, useMessages } from "gt-react-native";
9import { useRef, useState } from "react";
10import { View } from "react-native";
11
12import { AppBar, type AppBarMenu } from "../../components/ui/AppBar";
13import { m } from "../../i18n/messages";
14import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal";
15import { useAttachmentDocument } from "../../lib/attachmentDocument";
16import { nativeViewerErrorMessage } from "../../lib/attachmentDownload";
17import { isFileBackedComposerAttachment } from "../../lib/composerImages";
18import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
19import { removeComposerDraftAttachment, useComposerDraft } from "../../state/use-composer-drafts";
20import { useEnvironmentServerConfig } from "../../state/entities";
21import { useRefreshAssetUrl } from "../../state/assets";
22import { scopedThreadKey } from "../../lib/scopedEntities";
23import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
24import { isZipFile, ZipArchiveView } from "./ZipArchiveView";
25import { AttachmentDocumentBody, nativeViewerKind } from "./AttachmentDocumentBody";
26
27export type AttachmentFileRouteParams = {
28 readonly environmentId?: string;
29 readonly threadId?: string;
30 readonly attachmentId: string;
31 readonly name: string;
32 readonly mimeType: string;
33 readonly sizeBytes: string;
34 readonly draftKey?: string;
35 readonly htmlRender?: "1";
36};
37
38type AttachmentFileScreenProps = StaticScreenProps<AttachmentFileRouteParams>;
39
40export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
41 const navigation = useNavigation();
42 const gt = useGT();
43 const messages = useMessages();
44 const { appearance, setCodeWordBreak } = useAppearancePreferences();
45 const params = props.route.params;
46 const environmentId = params.environmentId?.trim()
47 ? EnvironmentId.make(params.environmentId)
48 : null;
49 const sizeBytes = Number.parseInt(params.sizeBytes, 10) || 0;
50 const draftKey = params.draftKey ?? null;
51 const draft = useComposerDraft(draftKey);
52 const draftAttachment = draftKey
53 ? draft.attachments.find((entry) => entry.id === params.attachmentId)
54 : undefined;
55 const localAttachment =
56 draftAttachment && isFileBackedComposerAttachment(draftAttachment) ? draftAttachment : null;
57 const document = useAttachmentDocument({
58 name: params.name,
59 mimeType: params.mimeType,
60 sizeBytes,
61 attachmentId: params.attachmentId,
62 environmentId,
63 attachment: localAttachment,
64 });
65 const [nativeOpen, setNativeOpen] = useState(false);
66 const nativeKind = nativeViewerKind(document.kind);
67 const [nativeViewer, setNativeViewer] = useState<"pending" | "open" | "unavailable" | null>(
68 nativeKind ? "pending" : null,
69 );
70 const [nativeError, setNativeError] = useState<string | null>(null);
71 const pendingNativeError = useRef<string | null>(null);
72 const handleBack = () => {
73 if (navigation.canGoBack()) navigation.goBack();
74 };
75 const { uri, resource } = document;
76 // A file only the native viewer can show opens it as soon as the file resolves.
77 if (nativeViewer === "pending" && uri) {
78 setNativeViewer("open");
79 setNativeOpen(true);
80 }
81 // Mint a fresh URL: cached URLs may expire in the background before Quick Look or ACTION_VIEW opens.
82 const nativeSource = ((): FilePreviewSource | null => {
83 const kind = nativeKind ?? "document";
84 const base = { kind, name: params.name, mimeType: params.mimeType };
85 if (localAttachment) return { ...base, attachment: localAttachment };
86 if (environmentId) return { ...base, environmentId, resource };
87 return uri ? { ...base, uri } : null;
88 })();
89 const handleNativeOpenError = (error: unknown) => {
90 pendingNativeError.current = nativeViewerErrorMessage(error);
91 };
92 const handleNativeClose = () => {
93 setNativeOpen(false);
94 const message = pendingNativeError.current;
95 pendingNativeError.current = null;
96 if (nativeViewer === null) {
97 if (message) Dialog.alert(m(msg("Could not open document")), message);
98 return;
99 }
100 if (message) {
101 setNativeError(message);
102 setNativeViewer("unavailable");
103 return;
104 }
105 handleBack();
106 };
107 const removeFromDraft = () => {
108 if (!draftKey) return;
109 removeComposerDraftAttachment(draftKey, params.attachmentId);
110 handleBack();
111 };
112
113 const { content, renderedMode, activeMode, setRendered, share, sharing } = document;
114 const menuActions = [
115 renderedMode
116 ? ({
117 id: "preview",
118 title:
119 renderedMode === "table"
120 ? gt({ context: "file view mode" })`Table`
121 : gt({ context: "file view mode" })`Preview`,
122 icon: renderedMode === "table" ? "tablecells" : "eye",
123 inline: true,
124 onPress: () => setRendered(true),
125 } as const)
126 : null,
127 renderedMode
128 ? ({
129 id: "source",
130 title: gt({ context: "file view mode, raw source text" })`Source`,
131 icon: "doc.text",
132 inline: true,
133 onPress: () => setRendered(false),
134 } as const)
135 : null,
136 content && activeMode === "source"
137 ? ({
138 id: "word-wrap",
139 title: appearance.codeWordBreak ? gt`Disable word wrap` : gt`Enable word wrap`,
140 icon: "text.alignleft",
141 inline: false,
142 onPress: () => setCodeWordBreak(!appearance.codeWordBreak),
143 } as const)
144 : null,
145 content
146 ? ({
147 id: "copy",
148 title: content.truncated ? gt`Copy preview` : gt`Copy contents`,
149 icon: "doc.on.doc",
150 inline: false,
151 onPress: () => copyTextWithHaptic(content.text),
152 } as const)
153 : null,
154 uri
155 ? ({
156 id: "share",
157 title: sharing ? gt`Opening share sheet…` : gt`Save or share`,
158 icon: "square.and.arrow.up",
159 inline: false,
160 onPress: () => void share(),
161 } as const)
162 : null,
163 uri
164 ? ({
165 id: "open-viewer",
166 title: gt`Open in file viewer`,
167 icon: "arrow.up.left.and.arrow.down.right",
168 inline: false,
169 onPress: () => {
170 setNativeViewer((current) => (current === null ? null : "open"));
171 setNativeOpen(true);
172 },
173 } as const)
174 : null,
175 draftKey
176 ? ({
177 id: "remove",
178 title: gt`Remove from draft`,
179 icon: "trash",
180 inline: false,
181 destructive: true,
182 onPress: removeFromDraft,
183 } as const)
184 : null,
185 ].filter((action) => action !== null);
186 const selectedAction = activeMode === "source" ? "source" : "preview";
187 const fileMenu: AppBarMenu = {
188 title: gt`File actions`,
189 icon: "ellipsis",
190 items: [
191 ...(renderedMode
192 ? [
193 {
194 id: "modes",
195 inline: true,
196 items: menuActions
197 .filter(({ inline }) => inline)
198 .map((action) => ({
199 id: action.id,
200 title: action.title,
201 icon: action.icon,
202 selected: action.id === selectedAction,
203 onPress: action.onPress,
204 })),
205 },
206 ]
207 : []),
208 ...menuActions
209 .filter(({ inline }) => !inline)
210 .map((action) => ({
211 id: action.id,
212 title: action.title,
213 icon: action.icon,
214 destructive: "destructive" in action,
215 onPress: action.onPress,
216 })),
217 ],
218 };
219 const subtitle =
220 sizeBytes > 0
221 ? draftKey
222 ? gt`Draft attachment · ${{ size: formatAttachmentSize(sizeBytes, messages) }}`
223 : gt`Attachment · ${{ size: formatAttachmentSize(sizeBytes, messages) }}`
224 : draftKey
225 ? gt`Draft attachment`
226 : gt`Attachment`;
227 const refresh = useRefreshAssetUrl(environmentId, resource);
228 const capabilities = useEnvironmentServerConfig(environmentId)?.environment.capabilities;
229
230 if (document.kind === "archive" && isZipFile(params) && !document.error) {
231 const threadDraftKey =
232 environmentId && params.threadId
233 ? scopedThreadKey(environmentId, ThreadId.make(params.threadId))
234 : null;
235 return (
236 <ZipArchiveView
237 name={params.name}
238 subtitle={subtitle}
239 sizeBytes={sizeBytes}
240 uri={uri}
241 isLocal={localAttachment !== null}
242 refresh={refresh}
243 environmentId={environmentId}
244 // Entries go to the thread's chat composer, also from a question-answer draft.
245 draftKey={threadDraftKey ?? draftKey}
246 maxAttachmentBytes={
247 capabilities?.attachmentUploads && capabilities.fileAttachments
248 ? clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes)
249 : undefined
250 }
251 onSave={() => void share()}
252 onRemove={draftKey ? removeFromDraft : null}
253 />
254 );
255 }
256
257 return (
258 <View className="flex-1 bg-sheet">
259 <AppBar title={params.name} subtitle={subtitle} onBack={handleBack} menus={[fileMenu]} />
260 <AttachmentDocumentBody
261 document={document}
262 name={params.name}
263 environmentId={environmentId}
264 htmlRender={params.htmlRender === "1"}
265 nativeViewer={nativeViewer}
266 nativeError={nativeError}
267 onOpenNative={() => {
268 setNativeViewer((current) => (current === null ? null : "open"));
269 setNativeOpen(true);
270 }}
271 />
272 {nativeOpen && nativeSource ? (
273 <FilePreviewModal
274 source={nativeSource}
275 onRequestClose={handleNativeClose}
276 onOpenError={handleNativeOpenError}
277 />
278 ) : null}
279 </View>
280 );
281}