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

AttachmentFileScreen.tsx

283 lines9.9 KB

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