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