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