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

ZipArchiveView.tsx

912 lines31.6 KB

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