The best way to control Claude Code, Codex and more from any computer or phone

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