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

AttachmentFileScreen.tsx

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