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 { AppBar } from "../../components/ui/AppBar";
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 <AppBar
310 embedded
311 title={props.name}
312 subtitle={props.subtitle}
313 onBack={() => {
314 if (navigation.canGoBack()) navigation.goBack();
315 }}
316 actions={[
317 { accessibilityLabel: "Save ZIP", icon: "square.and.arrow.up", onPress: props.onSave },
318 ...(props.onRemove
319 ? [
320 {
321 accessibilityLabel: "Remove from draft",
322 icon: "trash" as const,
323 onPress: props.onRemove,
324 destructive: true,
325 overflowOnly: true,
326 },
327 ]
328 : []),
329 ]}
330 />
331 ) : (
332 <Toolbar placement="right">
333 {props.onRemove ? (
334 <Toolbar.Menu accessibilityLabel="ZIP actions" icon="ellipsis">
335 <Toolbar.MenuAction icon="square.and.arrow.up" onPress={props.onSave}>
336 Save ZIP
337 </Toolbar.MenuAction>
338 <Toolbar.MenuAction icon="trash" destructive onPress={props.onRemove}>
339 Remove from draft
340 </Toolbar.MenuAction>
341 </Toolbar.Menu>
342 ) : (
343 <Toolbar.Button
344 accessibilityLabel="Save ZIP"
345 icon="square.and.arrow.up"
346 onPress={props.onSave}
347 />
348 )}
349 </Toolbar>
350 )}
351 </>
352 );
353}
354
355function ZipArchiveProgress(props: {
356 readonly receivedBytes: number;
357 readonly totalBytes: number;
358 readonly timeLeft: string | null;
359 readonly onCancel: () => void;
360}) {
361 const { timeLeft } = props;
362 return (
363 <View className="flex-1 justify-center gap-3 bg-sheet px-8">
364 <Text className="text-xl font-t3-semibold text-foreground">
365 {formatAttachmentSize(props.receivedBytes)}
366 {props.totalBytes > 0 ? (
367 <Text className="text-xl text-foreground-muted">
368 {` of ${formatAttachmentSize(props.totalBytes)}`}
369 </Text>
370 ) : null}
371 </Text>
372 <Progress
373 value={props.totalBytes > 0 ? props.receivedBytes / props.totalBytes : undefined}
374 label="ZIP download progress"
375 />
376 <Text className="text-sm text-foreground-muted">
377 {`Downloading the ZIP so its files can be listed.${timeLeft ? ` ${timeLeft} on this connection.` : ""}`}
378 </Text>
379 <Button label="Cancel" onPress={props.onCancel} />
380 </View>
381 );
382}
383
384function ZipArchiveFailure(props: {
385 readonly failure: ZipFailure;
386 readonly onRetry: () => void;
387 readonly onSave: () => void;
388}) {
389 return (
390 <View className="flex-1 items-center justify-center bg-sheet px-6">
391 <EmptyState
392 variant="plain"
393 title={props.failure.title}
394 detail={props.failure.detail}
395 action={
396 <View className="flex-row gap-3">
397 {props.failure.retry ? (
398 <Button tone="primary" label="Try again" onPress={props.onRetry} />
399 ) : null}
400 <Button
401 tone={props.failure.retry ? "secondary" : "primary"}
402 label="Save ZIP"
403 onPress={props.onSave}
404 />
405 </View>
406 }
407 />
408 </View>
409 );
410}
411
412function ZipArchiveList(props: {
413 readonly archive: ZipArchive;
414 readonly headerInset: number;
415 readonly onOpen: (entry: ZipEntry) => void;
416}) {
417 const [query, setQuery] = useState("");
418 const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
419 const { archive } = props;
420 const rows = flattenZipTree(buildZipTree(archive.entries), collapsed, query);
421 const toggle = (path: string) =>
422 setCollapsed((current) => {
423 const next = new Set(current);
424 if (!next.delete(path)) next.add(path);
425 return next;
426 });
427 const fileCount = archive.fileCount;
428 return (
429 <View className="flex-1 bg-sheet">
430 <LegendList
431 renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
432 contentInsetStartAdjustment={props.headerInset}
433 className="flex-1"
434 data={rows}
435 keyExtractor={(row) => `${row.node.entry ? "f" : "d"}:${row.node.path}`}
436 contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
437 automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
438 estimatedItemSize={44}
439 recycleItems
440 keyboardDismissMode="on-drag"
441 keyboardShouldPersistTaps="handled"
442 extraData={collapsed}
443 contentContainerStyle={{ paddingBottom: 4 }}
444 ListHeaderComponent={
445 <View className="px-4 pt-3 pb-2.5">
446 <View className="h-[38px] flex-row items-center gap-2 rounded-[10px] bg-subtle px-3">
447 <SymbolView name="magnifyingglass" size={15} tintColorClassName="accent-icon-muted" />
448 <TextInput
449 accessibilityLabel="Filter files in ZIP"
450 autoCapitalize="none"
451 autoCorrect={false}
452 placeholder={`Filter ${fileCount} ${fileCount === 1 ? "file" : "files"}`}
453 placeholderTextColorClassName="accent-placeholder"
454 cursorColorClassName="accent-focus"
455 className="min-w-0 flex-1 font-sans text-[15px] text-foreground"
456 value={query}
457 onChangeText={setQuery}
458 />
459 {query ? (
460 <Pressable
461 accessibilityRole="button"
462 accessibilityLabel="Clear filter"
463 hitSlop={10}
464 onPress={() => setQuery("")}
465 >
466 <SymbolView
467 name="xmark.circle.fill"
468 size={16}
469 tintColorClassName="accent-icon-muted"
470 />
471 </Pressable>
472 ) : null}
473 </View>
474 </View>
475 }
476 renderItem={({ item }) => (
477 <ZipTreeRowView
478 row={item}
479 collapsed={collapsed.has(item.node.path)}
480 onToggle={toggle}
481 onOpen={props.onOpen}
482 />
483 )}
484 ListEmptyComponent={
485 query ? (
486 <EmptyState
487 variant="plain"
488 title={`No files match “${query.trim()}”`}
489 detail="The filter checks file names and folder paths."
490 action={<Button label="Clear filter" onPress={() => setQuery("")} />}
491 />
492 ) : (
493 <EmptyState variant="plain" title="This ZIP is empty" detail="It has no files." />
494 )
495 }
496 />
497 </View>
498 );
499}
500
501export function ZipArchiveView(props: {
502 readonly name: string;
503 readonly subtitle: string;
504 readonly tintColor: string;
505 readonly sizeBytes: number;
506 readonly uri: string | null;
507 readonly isLocal: boolean;
508 readonly refresh: () => Promise<string | null>;
509 readonly environmentId: EnvironmentId | null;
510 readonly draftKey: string | null;
511 readonly maxAttachmentBytes: number | undefined;
512 readonly onSave: () => void;
513 readonly onRemove: (() => void) | null;
514}) {
515 const { state, retry, cancel } = useZipArchive(props);
516 const [selection, setSelection] = useState<{
517 readonly archive: ZipArchive;
518 readonly entry: ZipEntry;
519 } | null>(null);
520 const archive = state.status === "ready" ? state.archive : null;
521 const selected = selection && selection.archive === archive ? selection.entry : null;
522 const entryOpen = selected !== null;
523 usePreventRemove(entryOpen, () => setSelection(null));
524 const insets = useSafeAreaInsets();
525 const columnMetrics = useNativeColumnLayoutMetrics();
526 const headerInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
527 return (
528 <View className="flex-1 bg-sheet">
529 {entryOpen ? null : (
530 <ZipArchiveHeader
531 name={props.name}
532 subtitle={
533 archive
534 ? `${archive.fileCount} ${archive.fileCount === 1 ? "file" : "files"}${props.sizeBytes > 0 ? ` · ${formatAttachmentSize(props.sizeBytes)}` : ""}`
535 : props.subtitle
536 }
537 tintColor={props.tintColor}
538 onSave={props.onSave}
539 onRemove={props.onRemove}
540 />
541 )}
542 {state.status === "ready" ? (
543 <ZipArchiveList
544 archive={state.archive}
545 headerInset={headerInset}
546 onOpen={(entry) => {
547 Keyboard.dismiss();
548 setSelection({ archive: state.archive, entry });
549 }}
550 />
551 ) : (
552 <View className="flex-1" style={{ paddingTop: headerInset }}>
553 {state.status === "loading" ? (
554 props.isLocal || state.receivedBytes === 0 ? (
555 <FilePreviewLoading message="Opening ZIP..." />
556 ) : (
557 <ZipArchiveProgress
558 receivedBytes={state.receivedBytes}
559 totalBytes={props.sizeBytes}
560 timeLeft={state.timeLeft}
561 onCancel={cancel}
562 />
563 )
564 ) : (
565 <ZipArchiveFailure failure={state.failure} onRetry={retry} onSave={props.onSave} />
566 )}
567 </View>
568 )}
569 {selected ? (
570 <View className="absolute inset-0">
571 <ZipEntryView
572 key={selected.path}
573 archiveName={props.name}
574 entry={selected}
575 environmentId={props.environmentId}
576 draftKey={props.draftKey}
577 maxAttachmentBytes={props.maxAttachmentBytes}
578 onBack={() => setSelection(null)}
579 />
580 </View>
581 ) : null}
582 </View>
583 );
584}
585
586async function addZipEntryToDraft(input: {
587 readonly entry: ZipEntry;
588 readonly draftKey: string;
589 readonly maxBytes: number;
590 readonly signal: AbortSignal;
591}) {
592 const { entry, signal } = input;
593 const file = await writeGeneratedAttachmentFile({
594 bytes: entry.bytes,
595 attachment: { name: entry.name, mimeType: entry.mimeType },
596 });
597 try {
598 signal.throwIfAborted();
599 const attachment = await createComposerFileAttachment({
600 uri: file.uri,
601 name: entry.name,
602 mimeType: entry.mimeType,
603 sizeBytes: entry.sizeBytes,
604 maxBytes: input.maxBytes,
605 });
606 if (signal.aborted) {
607 await removePersistedComposerAttachmentFile(attachment.fileUri);
608 signal.throwIfAborted();
609 }
610 // Rejected attachments are cleaned up by the draft store.
611 if (appendComposerDraftAttachments(input.draftKey, [attachment], { appendReference: true }))
612 throw new Error("This message already has as many attachments as it can hold.");
613 } finally {
614 file.dispose();
615 }
616}
617
618type EntryContent =
619 | { readonly status: "loading" }
620 | { readonly status: "text"; readonly text: string; readonly truncated: boolean }
621 | { readonly status: "file"; readonly uri: string }
622 | { readonly status: "failed"; readonly title: string; readonly message: string };
623
624function ZipEntryView(props: {
625 readonly archiveName: string;
626 readonly entry: ZipEntry;
627 readonly environmentId: EnvironmentId | null;
628 readonly draftKey: string | null;
629 readonly maxAttachmentBytes: number | undefined;
630 readonly onBack: () => void;
631}) {
632 const { entry, draftKey, maxAttachmentBytes } = props;
633 const { mimeType } = entry;
634 const previewKind = filePreviewKind({ name: entry.name, mimeType });
635 const isText = previewKind === "text" || previewKind === "markdown" || previewKind === "html";
636 // Archive HTML is shown as source: a rendered page could load its sibling files.
637 const kind = previewKind === "html" ? "text" : previewKind;
638 const viewerKind = isText || kind === "audio" ? null : (nativeViewerKind(kind) ?? "document");
639 const tooBig = entry.sizeBytes > ARCHIVE_ENTRY_MAX_BYTES;
640 const [content, setContent] = useState<EntryContent>(
641 tooBig
642 ? {
643 status: "failed",
644 title: "Too big to preview",
645 message: `Previews stop at ${formatAttachmentSize(ARCHIVE_ENTRY_MAX_BYTES)}. Save the file to open it in another app.`,
646 }
647 : { status: "loading" },
648 );
649 const [rendered, setRendered] = useState(true);
650 const [revision, setRevision] = useState(0);
651 const [viewerOpen, setViewerOpen] = useState(true);
652 const [viewerError, setViewerError] = useState<string | null>(null);
653 const [busy, setBusy] = useState<"save" | "attach" | null>(null);
654 const action = useRef<AbortController | null>(null);
655 const pendingViewerError = useRef<string | null>(null);
656 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Cancel a pending save or attach when the entry closes.
657 useEffect(() => () => action.current?.abort(), []);
658 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Write the selected entry to a cached file and release it on cleanup.
659 useEffect(() => {
660 if (tooBig) return;
661 const controller = new AbortController();
662 let release: (() => void) | undefined;
663 void (async (): Promise<EntryContent> => {
664 if (isText) return { status: "text", ...decodeFilePreviewText(entry.bytes) };
665 const file = await writeGeneratedAttachmentFile({
666 bytes: entry.bytes,
667 attachment: { name: entry.name, mimeType },
668 });
669 if (controller.signal.aborted) {
670 file.dispose();
671 controller.signal.throwIfAborted();
672 }
673 release = file.dispose;
674 return { status: "file", uri: file.uri };
675 })()
676 .then((value) => {
677 if (!controller.signal.aborted) setContent(value);
678 })
679 .catch((cause: unknown) => {
680 if (!controller.signal.aborted)
681 setContent({
682 status: "failed",
683 title: "Couldn't read this file",
684 message: errorMessage(cause, "Could not read this file."),
685 });
686 });
687 return () => {
688 controller.abort();
689 release?.();
690 };
691 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reread the entry.
692 }, [entry, isText, mimeType, tooBig, revision]);
693
694 const run = (kind: "save" | "attach", task: (signal: AbortSignal) => Promise<unknown>) => {
695 if (busy) return;
696 setBusy(kind);
697 const controller = new AbortController();
698 action.current = controller;
699 void task(controller.signal).then(
700 () => {
701 if (controller.signal.aborted) return;
702 setBusy(null);
703 if (kind === "attach")
704 Dialog.alert("Added to chat", `${entry.name} is attached to your message.`);
705 },
706 (cause: unknown) => {
707 if (controller.signal.aborted) return;
708 setBusy(null);
709 Dialog.alert(
710 kind === "save" ? "Could not save file" : "Could not add file to chat",
711 errorMessage(cause, "Please try again."),
712 );
713 },
714 );
715 };
716 const save = () =>
717 run("save", (signal) =>
718 shareGeneratedAttachment({
719 bytes: entry.bytes,
720 attachment: { name: entry.name, mimeType },
721 signal,
722 }),
723 );
724 const canAddToChat = draftKey !== null && maxAttachmentBytes !== undefined;
725 const addToChat = () => {
726 if (draftKey === null || maxAttachmentBytes === undefined) return;
727 run("attach", (signal) =>
728 addZipEntryToDraft({ entry, draftKey, maxBytes: maxAttachmentBytes, signal }),
729 );
730 };
731 const openViewer = () => {
732 setViewerError(null);
733 setViewerOpen(true);
734 };
735
736 const text = content.status === "text" ? content : null;
737 const delimiter = filePreviewDelimiter({ name: entry.name, mimeType });
738 const table = text && delimiter ? parseDelimitedPreview(text.text, delimiter) : null;
739 const uri = content.status === "file" ? content.uri : null;
740 const { renderedMode, activeMode } = attachmentDocumentPresentation({
741 kind,
742 hasTable: table !== null,
743 hasEnvironment: props.environmentId !== null,
744 rendered,
745 });
746 const folders = entry.path.split("/").slice(0, -1);
747 const subtitle = `${[props.archiveName, ...folders].join(" / ")} · ${formatAttachmentSize(entry.sizeBytes)}`;
748 const isAndroid = Platform.OS === "android";
749 return (
750 <View className="flex-1 bg-sheet">
751 <NativeStackScreenOptions
752 options={{
753 headerShown: !isAndroid,
754 headerTitle: entry.name,
755 title: entry.name,
756 unstable_headerSubtitle: isAndroid ? undefined : subtitle,
757 }}
758 />
759 {isAndroid ? (
760 <AppBar
761 embedded
762 title={entry.name}
763 subtitle={subtitle}
764 onBack={props.onBack}
765 actions={[
766 ...(renderedMode
767 ? [
768 {
769 accessibilityLabel: rendered ? "Show source" : "Show preview",
770 icon: rendered ? ("doc.text" as const) : ("eye" as const),
771 onPress: () => setRendered((value) => !value),
772 },
773 ]
774 : []),
775 ...(canAddToChat
776 ? [
777 {
778 accessibilityLabel: "Add to chat",
779 icon: "plus.bubble" as const,
780 onPress: addToChat,
781 disabled: busy !== null,
782 },
783 ]
784 : []),
785 {
786 accessibilityLabel: "Save file",
787 icon: "square.and.arrow.up",
788 onPress: save,
789 loading: busy === "save",
790 },
791 ]}
792 />
793 ) : (
794 <Toolbar placement="right">
795 <Toolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
796 {renderedMode ? (
797 <Toolbar.MenuAction
798 icon={rendered ? "doc.text" : "eye"}
799 onPress={() => setRendered((value) => !value)}
800 >
801 {rendered ? "Show source" : "Show preview"}
802 </Toolbar.MenuAction>
803 ) : null}
804 {canAddToChat ? (
805 <Toolbar.MenuAction icon="plus.bubble" disabled={busy !== null} onPress={addToChat}>
806 Add to chat
807 </Toolbar.MenuAction>
808 ) : null}
809 <Toolbar.MenuAction icon="square.and.arrow.up" disabled={busy !== null} onPress={save}>
810 Save file
811 </Toolbar.MenuAction>
812 </Toolbar.Menu>
813 </Toolbar>
814 )}
815 {content.status === "failed" ? (
816 <ScrollView contentContainerClassName="flex-grow items-center justify-center px-6">
817 <EmptyState
818 variant="plain"
819 title={content.title}
820 detail={content.message}
821 action={
822 <Button tone="primary" label="Save file" loading={busy === "save"} onPress={save} />
823 }
824 />
825 </ScrollView>
826 ) : viewerKind && uri && !viewerOpen ? (
827 // Closing the viewer stays here so Save and Add to chat remain reachable.
828 <View className="flex-1 items-center justify-center bg-sheet px-6">
829 <EmptyState
830 title={viewerError ? "No preview for this file" : entry.name}
831 detail={viewerError ?? "Open it in the file viewer, save it, or add it to chat."}
832 actionLabel="Open in file viewer"
833 onAction={openViewer}
834 />
835 </View>
836 ) : (
837 <AttachmentDocumentBody
838 document={{
839 kind,
840 activeMode,
841 uri,
842 content: text,
843 table,
844 error: null,
845 needsText: isText,
846 retry: () => setRevision((value) => value + 1),
847 revision,
848 }}
849 name={entry.name}
850 environmentId={props.environmentId}
851 htmlRender={false}
852 nativeViewer={viewerKind ? (uri ? "open" : "pending") : null}
853 nativeError={null}
854 onOpenNative={openViewer}
855 />
856 )}
857 {viewerKind && uri && viewerOpen ? (
858 <FilePreviewModal
859 source={{ kind: viewerKind, name: entry.name, mimeType, uri }}
860 onOpenError={(error) => {
861 pendingViewerError.current = nativeViewerErrorMessage(error);
862 }}
863 onRequestClose={() => {
864 setViewerError(pendingViewerError.current);
865 pendingViewerError.current = null;
866 setViewerOpen(false);
867 }}
868 />
869 ) : null}
870 </View>
871 );
872}