Open History to see the last commit
1import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
2import {
3 ARCHIVE_ENTRY_MAX_BYTES,
4 ARCHIVE_MAX_BYTES,
5 boundedZip,
6} from "@t3tools/client-runtime/zip/bounded-zip";
7import type { EnvironmentId } from "@t3tools/contracts";
8import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
9import {
10 decodeFilePreviewText,
11 filePreviewKind,
12 hostPreviewMimeTypeFromExtension,
13} from "@t3tools/shared/filePreview";
14import { LegendList } from "@legendapp/list/react-native";
15import { fetch } from "expo/fetch";
16import { File } from "expo-file-system";
17import { useNavigation, usePreventRemove } from "@react-navigation/native";
18import { useEffect, useEffectEvent, useRef, useState } from "react";
19import { Keyboard, Platform, Pressable, ScrollView, TextInput, View } from "react-native";
20import { useSafeAreaInsets } from "react-native-safe-area-context";
21
22import { PierreEntryIcon } from "../../components/PierreEntryIcon";
23import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
24import { SymbolView } from "../../components/ui/AppSymbol";
25import { AppText as Text } from "../../components/ui/AppText";
26import { Button } from "../../components/ui/Button";
27import { EmptyState } from "../../components/ui/EmptyState";
28import { Progress } from "../../components/ui/Progress";
29import { Toolbar } from "../../components/ui/Toolbar";
30import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
31import { NativeScrollView } from "../../native/NativeScrollViewMarker";
32import { NativeStackScreenOptions } from "../../native/StackHeader";
33import * as Dialog from "../../components/ui/Dialog";
34import { FilePreviewModal } from "../../components/FilePreviewModal";
35import {
36 nativeViewerErrorMessage,
37 shareGeneratedAttachment,
38 writeGeneratedAttachmentFile,
39} from "../../lib/attachmentDownload";
40import { attachmentDocumentPresentation } from "../../lib/attachmentDocumentPresentation";
41import {
42 createComposerFileAttachment,
43 removePersistedComposerAttachmentFile,
44} from "../../lib/composerImages";
45import { appendComposerDraftAttachments } from "../../state/use-composer-drafts";
46import { AttachmentDocumentBody, nativeViewerKind } from "./AttachmentDocumentBody";
47import { FilePreviewLoading } from "./FilePreviewFeedback";
48import {
49 buildZipTree,
50 flattenZipTree,
51 zipDownloadTimeLeft,
52 zipFolderLabel,
53 type ZipEntry,
54 type ZipTreeRow,
55} from "./zipTree";
56
57export function isZipFile(file: { readonly name: string; readonly mimeType: string }) {
58 const mime = file.mimeType.split(";", 1)[0]?.trim().toLowerCase();
59 return (
60 mime === "application/zip" ||
61 mime === "application/x-zip-compressed" ||
62 file.name.toLowerCase().endsWith(".zip")
63 );
64}
65
66interface ZipArchive {
67 readonly entries: ReadonlyArray<ZipEntry>;
68 readonly fileCount: number;
69}
70
71interface ZipFailure {
72 readonly title: string;
73 readonly detail: string;
74 readonly retry: boolean;
75}
76
77const SAVE_ZIP_HINT = "Save the ZIP to open it in another app.";
78const TOO_LARGE: ZipFailure = {
79 title: "Too large to browse here",
80 detail: `Browsing works up to ${formatAttachmentSize(ARCHIVE_MAX_BYTES)}. ${SAVE_ZIP_HINT}`,
81 retry: false,
82};
83const CANCELLED: ZipFailure = {
84 title: "Download cancelled",
85 detail: "The ZIP wasn't downloaded. Try again to list its files.",
86 retry: true,
87};
88const NETWORK: ZipFailure = {
89 title: "Couldn't download this ZIP",
90 detail: "Check the connection to this environment and try again.",
91 retry: true,
92};
93
94class ZipFailureError extends Error {
95 constructor(readonly failure: ZipFailure) {
96 super(failure.title);
97 }
98}
99
100function errorMessage(cause: unknown, fallback: string) {
101 return cause instanceof Error ? cause.message : fallback;
102}
103
104async function readArchiveBody(
105 body: ReadableStream<Uint8Array>,
106 onProgress: (receivedBytes: number) => void,
107) {
108 const reader = body.getReader();
109 const chunks: Uint8Array[] = [];
110 let size = 0;
111 try {
112 while (true) {
113 const { value, done } = await reader.read();
114 if (done) break;
115 size += value.byteLength;
116 if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
117 chunks.push(value);
118 onProgress(size);
119 }
120 } finally {
121 void reader.cancel().catch(() => {});
122 }
123 const bytes = new Uint8Array(size);
124 let offset = 0;
125 for (const chunk of chunks) {
126 bytes.set(chunk, offset);
127 offset += chunk.byteLength;
128 }
129 return bytes.buffer;
130}
131
132async function openArchive(bytes: ArrayBuffer): Promise<ZipArchive> {
133 let files: Awaited<ReturnType<typeof boundedZip>>;
134 try {
135 files = await boundedZip(bytes);
136 } catch (cause) {
137 throw new ZipFailureError({
138 title: "Couldn't browse this ZIP",
139 detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`,
140 retry: false,
141 });
142 }
143 const entries = [...files].map(([path, file]): ZipEntry => {
144 const name = path.split("/").findLast(Boolean) ?? path;
145 const dot = name.lastIndexOf(".");
146 return {
147 path,
148 name,
149 isDirectory: file.directory,
150 sizeBytes: file.bytes.byteLength,
151 mimeType:
152 (dot > 0 ? hostPreviewMimeTypeFromExtension(name.slice(dot).toLowerCase()) : null) ??
153 "application/octet-stream",
154 bytes: file.bytes,
155 };
156 });
157 return { entries, fileCount: entries.filter((entry) => !entry.isDirectory).length };
158}
159
160type ArchiveState =
161 | { readonly status: "loading"; readonly receivedBytes: number; readonly timeLeft: string | null }
162 | { readonly status: "ready"; readonly archive: ZipArchive }
163 | { readonly status: "failed"; readonly failure: ZipFailure };
164
165function useZipArchive(input: {
166 readonly uri: string | null;
167 readonly isLocal: boolean;
168 readonly sizeBytes: number;
169 readonly refresh: () => Promise<string | null>;
170}) {
171 const [state, setState] = useState<ArchiveState>({
172 status: "loading",
173 receivedBytes: 0,
174 timeLeft: null,
175 });
176 const [revision, setRevision] = useState(0);
177 const controller = useRef<AbortController | null>(null);
178 const { uri, isLocal, sizeBytes } = input;
179 // The parent mints a new refresh callback on every render; it must not reload the archive.
180 const refresh = useEffectEvent(input.refresh);
181 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Load archive bytes and cancel the stream on cleanup.
182 useEffect(() => {
183 if (!uri) return;
184 const abort = new AbortController();
185 controller.current = abort;
186 const startedAt = Date.now();
187 // oxlint-disable-next-line react/set-state-in-effect -- A new archive load resets its progress.
188 setState({ status: "loading", receivedBytes: 0, timeLeft: null });
189 void (async () => {
190 if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
191 if (isLocal) {
192 const file = new File(uri);
193 if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
194 return openArchive(await file.arrayBuffer());
195 }
196 const url = (await refresh()) ?? uri;
197 const response = await fetch(url, { signal: abort.signal });
198 if (!response.ok || !response.body) throw new ZipFailureError(NETWORK);
199 const bytes = await readArchiveBody(response.body, (receivedBytes) =>
200 setState({
201 status: "loading",
202 receivedBytes,
203 timeLeft: zipDownloadTimeLeft({
204 receivedBytes,
205 totalBytes: sizeBytes,
206 elapsedMs: Date.now() - startedAt,
207 }),
208 }),
209 );
210 abort.signal.throwIfAborted();
211 return openArchive(bytes);
212 })()
213 .then((archive) => {
214 if (!abort.signal.aborted) setState({ status: "ready", archive });
215 })
216 .catch((cause: unknown) => {
217 if (!abort.signal.aborted)
218 setState({
219 status: "failed",
220 failure: cause instanceof ZipFailureError ? cause.failure : NETWORK,
221 });
222 });
223 return () => abort.abort();
224 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reload the archive.
225 }, [uri, isLocal, sizeBytes, revision]);
226 return {
227 state,
228 retry: () => setRevision((value) => value + 1),
229 cancel: () => {
230 controller.current?.abort();
231 setState({ status: "failed", failure: CANCELLED });
232 },
233 };
234}
235
236function ZipTreeRowView(props: {
237 readonly row: ZipTreeRow;
238 readonly collapsed: boolean;
239 readonly onToggle: (path: string) => void;
240 readonly onOpen: (entry: ZipEntry) => void;
241}) {
242 const { node, depth } = props.row;
243 const entry = node.entry;
244 const folder = entry ? null : zipFolderLabel(node.label);
245 return (
246 <Pressable
247 accessibilityRole="button"
248 accessibilityLabel={entry ? entry.path : `${node.path} folder`}
249 accessibilityState={entry ? undefined : { expanded: !props.collapsed }}
250 onPress={() => (entry ? props.onOpen(entry) : props.onToggle(node.path))}
251 className="mx-2 h-11 flex-row items-center gap-1.5 rounded-lg pr-2.5 active:bg-subtle"
252 style={{ paddingLeft: 8 + depth * 18 }}
253 >
254 <View className="w-4 items-center">
255 {entry ? null : (
256 <SymbolView
257 name={props.collapsed ? "chevron.right" : "chevron.down"}
258 size={12}
259 tintColorClassName="accent-icon-muted"
260 type="monochrome"
261 />
262 )}
263 </View>
264 <View className="w-5 items-center">
265 <PierreEntryIcon path={node.path} kind={entry ? "file" : "directory"} size={17} />
266 </View>
267 <Text className="min-w-0 flex-1 text-[15px] text-foreground" numberOfLines={1}>
268 {folder ? (
269 <>
270 <Text className="text-[15px] text-foreground-muted">{folder.prefix}</Text>
271 {folder.name}
272 </>
273 ) : (
274 node.label
275 )}
276 </Text>
277 <Text className="text-xs text-foreground-muted">
278 {entry
279 ? formatAttachmentSize(entry.sizeBytes)
280 : props.collapsed
281 ? `${node.fileCount} ${node.fileCount === 1 ? "file" : "files"}`
282 : ""}
283 </Text>
284 </Pressable>
285 );
286}
287
288function ZipArchiveHeader(props: {
289 readonly name: string;
290 readonly subtitle: string;
291 readonly tintColor: string;
292 readonly onSave: () => void;
293 readonly onRemove: (() => void) | null;
294}) {
295 const navigation = useNavigation();
296 const isAndroid = Platform.OS === "android";
297 return (
298 <>
299 <NativeStackScreenOptions
300 options={{
301 headerShown: !isAndroid,
302 headerTintColor: props.tintColor,
303 headerTitle: props.name,
304 title: props.name,
305 unstable_headerSubtitle: isAndroid ? undefined : props.subtitle,
306 }}
307 />
308 {isAndroid ? (
309 <AndroidScreenHeader
310 title={props.name}
311 subtitle={props.subtitle}
312 onBack={() => {
313 if (navigation.canGoBack()) navigation.goBack();
314 }}
315 actions={[
316 { accessibilityLabel: "Save ZIP", icon: "square.and.arrow.up", onPress: props.onSave },
317 ...(props.onRemove
318 ? [
319 {
320 accessibilityLabel: "Remove from draft",
321 icon: "trash" as const,
322 onPress: props.onRemove,
323 destructive: true,
324 overflowOnly: true,
325 },
326 ]
327 : []),
328 ]}
329 />
330 ) : (
331 <Toolbar placement="right">
332 {props.onRemove ? (
333 <Toolbar.Menu accessibilityLabel="ZIP actions" icon="ellipsis">
334 <Toolbar.MenuAction icon="square.and.arrow.up" onPress={props.onSave}>
335 Save ZIP
336 </Toolbar.MenuAction>
337 <Toolbar.MenuAction icon="trash" destructive onPress={props.onRemove}>
338 Remove from draft
339 </Toolbar.MenuAction>
340 </Toolbar.Menu>
341 ) : (
342 <Toolbar.Button
343 accessibilityLabel="Save ZIP"
344 icon="square.and.arrow.up"
345 onPress={props.onSave}
346 />
347 )}
348 </Toolbar>
349 )}
350 </>
351 );
352}
353
354function ZipArchiveProgress(props: {
355 readonly receivedBytes: number;
356 readonly totalBytes: number;
357 readonly timeLeft: string | null;
358 readonly onCancel: () => void;
359}) {
360 const { timeLeft } = props;
361 return (
362 <View className="flex-1 justify-center gap-3 bg-sheet px-8">
363 <Text className="text-xl font-t3-semibold text-foreground">
364 {formatAttachmentSize(props.receivedBytes)}
365 {props.totalBytes > 0 ? (
366 <Text className="text-xl text-foreground-muted">
367 {` of ${formatAttachmentSize(props.totalBytes)}`}
368 </Text>
369 ) : null}
370 </Text>
371 <Progress
372 value={props.totalBytes > 0 ? props.receivedBytes / props.totalBytes : undefined}
373 label="ZIP download progress"
374 />
375 <Text className="text-sm text-foreground-muted">
376 {`Downloading the ZIP so its files can be listed.${timeLeft ? ` ${timeLeft} on this connection.` : ""}`}
377 </Text>
378 <Button label="Cancel" onPress={props.onCancel} />
379 </View>
380 );
381}
382
383function ZipArchiveFailure(props: {
384 readonly failure: ZipFailure;
385 readonly onRetry: () => void;
386 readonly onSave: () => void;
387}) {
388 return (
389 <View className="flex-1 items-center justify-center bg-sheet px-6">
390 <EmptyState
391 variant="plain"
392 title={props.failure.title}
393 detail={props.failure.detail}
394 action={
395 <View className="flex-row gap-3">
396 {props.failure.retry ? (
397 <Button tone="primary" label="Try again" onPress={props.onRetry} />
398 ) : null}
399 <Button
400 tone={props.failure.retry ? "secondary" : "primary"}
401 label="Save ZIP"
402 onPress={props.onSave}
403 />
404 </View>
405 }
406 />
407 </View>
408 );
409}
410
411function ZipArchiveList(props: {
412 readonly archive: ZipArchive;
413 readonly headerInset: number;
414 readonly onOpen: (entry: ZipEntry) => void;
415}) {
416 const [query, setQuery] = useState("");
417 const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
418 const { archive } = props;
419 const rows = flattenZipTree(buildZipTree(archive.entries), collapsed, query);
420 const toggle = (path: string) =>
421 setCollapsed((current) => {
422 const next = new Set(current);
423 if (!next.delete(path)) next.add(path);
424 return next;
425 });
426 const fileCount = archive.fileCount;
427 return (
428 <View className="flex-1 bg-sheet">
429 <LegendList
430 renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
431 contentInsetStartAdjustment={props.headerInset}
432 className="flex-1"
433 data={rows}
434 keyExtractor={(row) => `${row.node.entry ? "f" : "d"}:${row.node.path}`}
435 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
436 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
437 estimatedItemSize={44}
438 recycleItems
439 keyboardDismissMode="on-drag"
440 keyboardShouldPersistTaps="handled"
441 extraData={collapsed}
442 contentContainerStyle={{ paddingBottom: 4 }}
443 ListHeaderComponent={
444 <View className="px-4 pt-3 pb-2.5">
445 <View className="h-[38px] flex-row items-center gap-2 rounded-[10px] bg-subtle px-3">
446 <SymbolView name="magnifyingglass" size={15} tintColorClassName="accent-icon-muted" />
447 <TextInput
448 accessibilityLabel="Filter files in ZIP"
449 autoCapitalize="none"
450 autoCorrect={false}
451 placeholder={`Filter ${fileCount} ${fileCount === 1 ? "file" : "files"}`}
452 placeholderTextColorClassName="accent-placeholder"
453 cursorColorClassName="accent-focus"
454 className="min-w-0 flex-1 font-sans text-[15px] text-foreground"
455 value={query}
456 onChangeText={setQuery}
457 />
458 {query ? (
459 <Pressable
460 accessibilityRole="button"
461 accessibilityLabel="Clear filter"
462 hitSlop={10}
463 onPress={() => setQuery("")}
464 >
465 <SymbolView
466 name="xmark.circle.fill"
467 size={16}
468 tintColorClassName="accent-icon-muted"
469 />
470 </Pressable>
471 ) : null}
472 </View>
473 </View>
474 }
475 renderItem={({ item }) => (
476 <ZipTreeRowView
477 row={item}
478 collapsed={collapsed.has(item.node.path)}
479 onToggle={toggle}
480 onOpen={props.onOpen}
481 />
482 )}
483 ListEmptyComponent={
484 query ? (
485 <EmptyState
486 variant="plain"
487 title={`No files match “${query.trim()}”`}
488 detail="The filter checks file names and folder paths."
489 action={<Button label="Clear filter" onPress={() => setQuery("")} />}
490 />
491 ) : (
492 <EmptyState variant="plain" title="This ZIP is empty" detail="It has no files." />
493 )
494 }
495 />
496 </View>
497 );
498}
499
500export function ZipArchiveView(props: {
501 readonly name: string;
502 readonly subtitle: string;
503 readonly tintColor: string;
504 readonly sizeBytes: number;
505 readonly uri: string | null;
506 readonly isLocal: boolean;
507 readonly refresh: () => Promise<string | null>;
508 readonly environmentId: EnvironmentId | null;
509 readonly draftKey: string | null;
510 readonly maxAttachmentBytes: number | undefined;
511 readonly onSave: () => void;
512 readonly onRemove: (() => void) | null;
513}) {
514 const { state, retry, cancel } = useZipArchive(props);
515 const [selection, setSelection] = useState<{
516 readonly archive: ZipArchive;
517 readonly entry: ZipEntry;
518 } | null>(null);
519 const archive = state.status === "ready" ? state.archive : null;
520 const selected = selection && selection.archive === archive ? selection.entry : null;
521 const entryOpen = selected !== null;
522 usePreventRemove(entryOpen, () => setSelection(null));
523 const insets = useSafeAreaInsets();
524 const columnMetrics = useNativeColumnLayoutMetrics();
525 const headerInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
526 return (
527 <View className="flex-1 bg-sheet">
528 {entryOpen ? null : (
529 <ZipArchiveHeader
530 name={props.name}
531 subtitle={
532 archive
533 ? `${archive.fileCount} ${archive.fileCount === 1 ? "file" : "files"}${props.sizeBytes > 0 ? ` · ${formatAttachmentSize(props.sizeBytes)}` : ""}`
534 : props.subtitle
535 }
536 tintColor={props.tintColor}
537 onSave={props.onSave}
538 onRemove={props.onRemove}
539 />
540 )}
541 {state.status === "ready" ? (
542 <ZipArchiveList
543 archive={state.archive}
544 headerInset={headerInset}
545 onOpen={(entry) => {
546 Keyboard.dismiss();
547 setSelection({ archive: state.archive, entry });
548 }}
549 />
550 ) : (
551 <View className="flex-1" style={{ paddingTop: headerInset }}>
552 {state.status === "loading" ? (
553 props.isLocal || state.receivedBytes === 0 ? (
554 <FilePreviewLoading message="Opening ZIP..." />
555 ) : (
556 <ZipArchiveProgress
557 receivedBytes={state.receivedBytes}
558 totalBytes={props.sizeBytes}
559 timeLeft={state.timeLeft}
560 onCancel={cancel}
561 />
562 )
563 ) : (
564 <ZipArchiveFailure failure={state.failure} onRetry={retry} onSave={props.onSave} />
565 )}
566 </View>
567 )}
568 {selected ? (
569 <View className="absolute inset-0">
570 <ZipEntryView
571 key={selected.path}
572 archiveName={props.name}
573 entry={selected}
574 environmentId={props.environmentId}
575 draftKey={props.draftKey}
576 maxAttachmentBytes={props.maxAttachmentBytes}
577 onBack={() => setSelection(null)}
578 />
579 </View>
580 ) : null}
581 </View>
582 );
583}
584
585async function addZipEntryToDraft(input: {
586 readonly entry: ZipEntry;
587 readonly draftKey: string;
588 readonly maxBytes: number;
589 readonly signal: AbortSignal;
590}) {
591 const { entry, signal } = input;
592 const file = await writeGeneratedAttachmentFile({
593 bytes: entry.bytes,
594 attachment: { name: entry.name, mimeType: entry.mimeType },
595 });
596 try {
597 signal.throwIfAborted();
598 const attachment = await createComposerFileAttachment({
599 uri: file.uri,
600 name: entry.name,
601 mimeType: entry.mimeType,
602 sizeBytes: entry.sizeBytes,
603 maxBytes: input.maxBytes,
604 });
605 if (signal.aborted) {
606 await removePersistedComposerAttachmentFile(attachment.fileUri);
607 signal.throwIfAborted();
608 }
609 // Rejected attachments are cleaned up by the draft store.
610 if (appendComposerDraftAttachments(input.draftKey, [attachment], { appendReference: true }))
611 throw new Error("This message already has as many attachments as it can hold.");
612 } finally {
613 file.dispose();
614 }
615}
616
617type EntryContent =
618 | { readonly status: "loading" }
619 | { readonly status: "text"; readonly text: string; readonly truncated: boolean }
620 | { readonly status: "file"; readonly uri: string }
621 | { readonly status: "failed"; readonly title: string; readonly message: string };
622
623function ZipEntryView(props: {
624 readonly archiveName: string;
625 readonly entry: ZipEntry;
626 readonly environmentId: EnvironmentId | null;
627 readonly draftKey: string | null;
628 readonly maxAttachmentBytes: number | undefined;
629 readonly onBack: () => void;
630}) {
631 const { entry, draftKey, maxAttachmentBytes } = props;
632 const { mimeType } = entry;
633 const previewKind = filePreviewKind({ name: entry.name, mimeType });
634 const isText = previewKind === "text" || previewKind === "markdown" || previewKind === "html";
635 // Archive HTML is shown as source: a rendered page could load its sibling files.
636 const kind = previewKind === "html" ? "text" : previewKind;
637 const viewerKind = isText || kind === "audio" ? null : (nativeViewerKind(kind) ?? "document");
638 const tooBig = entry.sizeBytes > ARCHIVE_ENTRY_MAX_BYTES;
639 const [content, setContent] = useState<EntryContent>(
640 tooBig
641 ? {
642 status: "failed",
643 title: "Too big to preview",
644 message: `Previews stop at ${formatAttachmentSize(ARCHIVE_ENTRY_MAX_BYTES)}. Save the file to open it in another app.`,
645 }
646 : { status: "loading" },
647 );
648 const [rendered, setRendered] = useState(true);
649 const [revision, setRevision] = useState(0);
650 const [viewerOpen, setViewerOpen] = useState(true);
651 const [viewerError, setViewerError] = useState<string | null>(null);
652 const [busy, setBusy] = useState<"save" | "attach" | null>(null);
653 const action = useRef<AbortController | null>(null);
654 const pendingViewerError = useRef<string | null>(null);
655 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Cancel a pending save or attach when the entry closes.
656 useEffect(() => () => action.current?.abort(), []);
657 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Write the selected entry to a cached file and release it on cleanup.
658 useEffect(() => {
659 if (tooBig) return;
660 const controller = new AbortController();
661 let release: (() => void) | undefined;
662 void (async (): Promise<EntryContent> => {
663 if (isText) return { status: "text", ...decodeFilePreviewText(entry.bytes) };
664 const file = await writeGeneratedAttachmentFile({
665 bytes: entry.bytes,
666 attachment: { name: entry.name, mimeType },
667 });
668 if (controller.signal.aborted) {
669 file.dispose();
670 controller.signal.throwIfAborted();
671 }
672 release = file.dispose;
673 return { status: "file", uri: file.uri };
674 })()
675 .then((value) => {
676 if (!controller.signal.aborted) setContent(value);
677 })
678 .catch((cause: unknown) => {
679 if (!controller.signal.aborted)
680 setContent({
681 status: "failed",
682 title: "Couldn't read this file",
683 message: errorMessage(cause, "Could not read this file."),
684 });
685 });
686 return () => {
687 controller.abort();
688 release?.();
689 };
690 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reread the entry.
691 }, [entry, isText, mimeType, tooBig, revision]);
692
693 const run = (kind: "save" | "attach", task: (signal: AbortSignal) => Promise<unknown>) => {
694 if (busy) return;
695 setBusy(kind);
696 const controller = new AbortController();
697 action.current = controller;
698 void task(controller.signal).then(
699 () => {
700 if (controller.signal.aborted) return;
701 setBusy(null);
702 if (kind === "attach")
703 Dialog.alert("Added to chat", `${entry.name} is attached to your message.`);
704 },
705 (cause: unknown) => {
706 if (controller.signal.aborted) return;
707 setBusy(null);
708 Dialog.alert(
709 kind === "save" ? "Could not save file" : "Could not add file to chat",
710 errorMessage(cause, "Please try again."),
711 );
712 },
713 );
714 };
715 const save = () =>
716 run("save", (signal) =>
717 shareGeneratedAttachment({
718 bytes: entry.bytes,
719 attachment: { name: entry.name, mimeType },
720 signal,
721 }),
722 );
723 const canAddToChat = draftKey !== null && maxAttachmentBytes !== undefined;
724 const addToChat = () => {
725 if (draftKey === null || maxAttachmentBytes === undefined) return;
726 run("attach", (signal) =>
727 addZipEntryToDraft({ entry, draftKey, maxBytes: maxAttachmentBytes, signal }),
728 );
729 };
730 const openViewer = () => {
731 setViewerError(null);
732 setViewerOpen(true);
733 };
734
735 const text = content.status === "text" ? content : null;
736 const delimiter = filePreviewDelimiter({ name: entry.name, mimeType });
737 const table = text && delimiter ? parseDelimitedPreview(text.text, delimiter) : null;
738 const uri = content.status === "file" ? content.uri : null;
739 const { renderedMode, activeMode } = attachmentDocumentPresentation({
740 kind,
741 hasTable: table !== null,
742 hasEnvironment: props.environmentId !== null,
743 rendered,
744 });
745 const folders = entry.path.split("/").slice(0, -1);
746 const subtitle = `${[props.archiveName, ...folders].join(" / ")} · ${formatAttachmentSize(entry.sizeBytes)}`;
747 const isAndroid = Platform.OS === "android";
748 return (
749 <View className="flex-1 bg-sheet">
750 <NativeStackScreenOptions
751 options={{
752 headerShown: !isAndroid,
753 headerTitle: entry.name,
754 title: entry.name,
755 unstable_headerSubtitle: isAndroid ? undefined : subtitle,
756 }}
757 />
758 {isAndroid ? (
759 <AndroidScreenHeader
760 title={entry.name}
761 subtitle={subtitle}
762 onBack={props.onBack}
763 actions={[
764 ...(renderedMode
765 ? [
766 {
767 accessibilityLabel: rendered ? "Show source" : "Show preview",
768 icon: rendered ? ("doc.text" as const) : ("eye" as const),
769 onPress: () => setRendered((value) => !value),
770 },
771 ]
772 : []),
773 ...(canAddToChat
774 ? [
775 {
776 accessibilityLabel: "Add to chat",
777 icon: "plus.bubble" as const,
778 onPress: addToChat,
779 disabled: busy !== null,
780 },
781 ]
782 : []),
783 {
784 accessibilityLabel: "Save file",
785 icon: "square.and.arrow.up",
786 onPress: save,
787 loading: busy === "save",
788 },
789 ]}
790 />
791 ) : (
792 <Toolbar placement="right">
793 <Toolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
794 {renderedMode ? (
795 <Toolbar.MenuAction
796 icon={rendered ? "doc.text" : "eye"}
797 onPress={() => setRendered((value) => !value)}
798 >
799 {rendered ? "Show source" : "Show preview"}
800 </Toolbar.MenuAction>
801 ) : null}
802 {canAddToChat ? (
803 <Toolbar.MenuAction icon="plus.bubble" disabled={busy !== null} onPress={addToChat}>
804 Add to chat
805 </Toolbar.MenuAction>
806 ) : null}
807 <Toolbar.MenuAction icon="square.and.arrow.up" disabled={busy !== null} onPress={save}>
808 Save file
809 </Toolbar.MenuAction>
810 </Toolbar.Menu>
811 </Toolbar>
812 )}
813 {content.status === "failed" ? (
814 <ScrollView contentContainerClassName="flex-grow items-center justify-center px-6">
815 <EmptyState
816 variant="plain"
817 title={content.title}
818 detail={content.message}
819 action={
820 <Button tone="primary" label="Save file" loading={busy === "save"} onPress={save} />
821 }
822 />
823 </ScrollView>
824 ) : viewerKind && uri && !viewerOpen ? (
825 // Closing the viewer stays here so Save and Add to chat remain reachable.
826 <View className="flex-1 items-center justify-center bg-sheet px-6">
827 <EmptyState
828 title={viewerError ? "No preview for this file" : entry.name}
829 detail={viewerError ?? "Open it in the file viewer, save it, or add it to chat."}
830 actionLabel="Open in file viewer"
831 onAction={openViewer}
832 />
833 </View>
834 ) : (
835 <AttachmentDocumentBody
836 document={{
837 kind,
838 activeMode,
839 uri,
840 content: text,
841 table,
842 error: null,
843 needsText: isText,
844 retry: () => setRevision((value) => value + 1),
845 revision,
846 }}
847 name={entry.name}
848 environmentId={props.environmentId}
849 htmlRender={false}
850 nativeViewer={viewerKind ? (uri ? "open" : "pending") : null}
851 nativeError={null}
852 onOpenNative={openViewer}
853 />
854 )}
855 {viewerKind && uri && viewerOpen ? (
856 <FilePreviewModal
857 source={{ kind: viewerKind, name: entry.name, mimeType, uri }}
858 onOpenError={(error) => {
859 pendingViewerError.current = nativeViewerErrorMessage(error);
860 }}
861 onRequestClose={() => {
862 setViewerError(pendingViewerError.current);
863 pendingViewerError.current = null;
864 setViewerOpen(false);
865 }}
866 />
867 ) : null}
868 </View>
869 );
870}