Skip to content
TypeScript

feat(mobile): browse ZIP attachments with the shared archive reader (#19463)

Bilal Bakr5b70d81b0d77
diff --git a/apps/mobile/src/features/files/AttachmentDocumentBody.tsx b/apps/mobile/src/features/files/AttachmentDocumentBody.tsx
new file mode 100644
index 00000000000..8cea0b4ce79
--- /dev/null
+++ b/apps/mobile/src/features/files/AttachmentDocumentBody.tsx
@@ -0,0 +1,111 @@
+import type { EnvironmentId } from "@t3tools/contracts";
+import { View } from "react-native";
+
+import { EmptyState } from "../../components/ui/EmptyState";
+import type { useAttachmentDocument } from "../../lib/attachmentDocument";
+import { HtmlRenderWebView } from "../threads/HtmlRenderWebView";
+import { AudioFilePreview } from "./AudioFilePreview";
+import { DelimitedFilePreview } from "./DelimitedFilePreview";
+import { FileMarkdownPreview } from "./FileMarkdownPreview";
+import { FilePreviewLoading, FilePreviewNotice } from "./FilePreviewFeedback";
+import { SourceFileSurface } from "./SourceFileSurface";
+import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
+
+export function nativeViewerKind(kind: ReturnType<typeof useAttachmentDocument>["kind"]) {
+ if (kind === "image") return "image" as const;
+ if (kind === "pdf") return "pdf" as const;
+ if (kind === "video" || kind === "unsupported") return "document" as const;
+ return null;
+}
+
+export function AttachmentDocumentBody(props: {
+ readonly document: Pick<
+ ReturnType<typeof useAttachmentDocument>,
+ | "kind"
+ | "activeMode"
+ | "uri"
+ | "content"
+ | "table"
+ | "error"
+ | "needsText"
+ | "retry"
+ | "revision"
+ >;
+ readonly name: string;
+ readonly environmentId: EnvironmentId | null;
+ readonly htmlRender: boolean;
+ readonly nativeViewer: "pending" | "open" | "unavailable" | null;
+ readonly nativeError: string | null;
+ readonly onOpenNative: () => void;
+}) {
+ const { document } = props;
+ if (document.error) {
+ return (
+ <View className="flex-1 items-center justify-center bg-sheet px-6">
+ <EmptyState
+ title="File unavailable"
+ detail={document.error}
+ actionLabel="Try again"
+ onAction={document.retry}
+ />
+ </View>
+ );
+ }
+ if (props.nativeViewer !== null && props.nativeViewer !== "unavailable") {
+ return <FilePreviewLoading message="Opening in file viewer..." />;
+ }
+ // ZIP text entries are read into memory and have no file URI.
+ if (document.needsText ? !document.content : !document.uri) {
+ return <FilePreviewLoading message="Loading file..." />;
+ }
+ if (document.needsText && document.content) {
+ const { content, table } = document;
+ return (
+ <View className="flex-1 bg-sheet">
+ {content.truncated ? (
+ <FilePreviewNotice title="Partial file">
+ Preview limited to the first 1 MB. Save or share the file to read it in full.
+ </FilePreviewNotice>
+ ) : null}
+ {table && document.activeMode === "table" ? (
+ <DelimitedFilePreview table={table} />
+ ) : document.activeMode === "markdown" && props.environmentId ? (
+ <FileMarkdownPreview
+ cwd=""
+ relativePath=""
+ environmentId={props.environmentId}
+ threadId={null}
+ markdown={content.text}
+ captured
+ />
+ ) : (
+ <SourceFileSurface contents={content.text} path={props.name} selectable />
+ )}
+ </View>
+ );
+ }
+ if (!document.uri) return null;
+ if (document.kind === "audio") {
+ return <AudioFilePreview key={document.revision} uri={document.uri} onRetry={document.retry} />;
+ }
+ if (document.kind === "html") {
+ return props.htmlRender ? (
+ <HtmlRenderWebView key={document.uri} uri={document.uri} title={props.name} nested={false} />
+ ) : (
+ <WorkspaceFileWebPreview uri={document.uri} />
+ );
+ }
+ return (
+ <View className="flex-1 items-center justify-center bg-sheet px-6">
+ <EmptyState
+ title="No preview for this file"
+ detail={
+ props.nativeError ??
+ "No app on this device can show this format. Save or share it to open it elsewhere."
+ }
+ actionLabel="Try again"
+ onAction={props.onOpenNative}
+ />
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/files/AttachmentFileScreen.tsx b/apps/mobile/src/features/files/AttachmentFileScreen.tsx
index 493efc7cf0d..a1d3978a57d 100644
--- a/apps/mobile/src/features/files/AttachmentFileScreen.tsx
+++ b/apps/mobile/src/features/files/AttachmentFileScreen.tsx
@@ -3,8 +3,11 @@ import * as Dialog from "../../components/ui/Dialog";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import type { MenuAction } from "@react-native-menu/menu";
-import { EnvironmentId } from "@t3tools/contracts";
-import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import {
+ clampFileAttachmentUploadBytes,
+ formatAttachmentSize,
+} from "@t3tools/client-runtime/state/attachments";
import { useRef, useState } from "react";
import { Platform, View } from "react-native";
@@ -12,10 +15,7 @@ import {
AndroidHeaderIconButton,
AndroidScreenHeader,
} from "../../components/ui/AndroidScreenHeader";
-import { DelimitedFilePreview } from "./DelimitedFilePreview";
-import { AudioFilePreview } from "./AudioFilePreview";
import { Menu } from "../../components/ui/Menu";
-import { EmptyState } from "../../components/ui/EmptyState";
import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
import { useAttachmentDocument } from "../../lib/attachmentDocument";
import { nativeViewerErrorMessage } from "../../lib/attachmentDownload";
@@ -23,12 +23,12 @@ import { isFileBackedComposerAttachment } from "../../lib/composerImages";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { removeComposerDraftAttachment, useComposerDraft } from "../../state/use-composer-drafts";
-import { FilePreviewLoading, FilePreviewNotice } from "./FilePreviewFeedback";
-import { FileMarkdownPreview } from "./FileMarkdownPreview";
+import { useEnvironmentServerConfig } from "../../state/entities";
+import { useRefreshAssetUrl } from "../../state/assets";
+import { scopedThreadKey } from "../../lib/scopedEntities";
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
-import { SourceFileSurface } from "./SourceFileSurface";
-import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
-import { HtmlRenderWebView } from "../threads/HtmlRenderWebView";
+import { isZipFile, ZipArchiveView } from "./ZipArchiveView";
+import { AttachmentDocumentBody, nativeViewerKind } from "./AttachmentDocumentBody";
export type AttachmentFileRouteParams = {
readonly environmentId?: string;
@@ -43,92 +43,6 @@ export type AttachmentFileRouteParams = {
type AttachmentFileScreenProps = StaticScreenProps<AttachmentFileRouteParams>;
-function nativeViewerKind(kind: ReturnType<typeof useAttachmentDocument>["kind"]) {
- if (kind === "image") return "image" as const;
- if (kind === "pdf") return "pdf" as const;
- if (kind === "video" || kind === "unsupported") return "document" as const;
- return null;
-}
-
-function AttachmentDocumentBody(props: {
- readonly document: ReturnType<typeof useAttachmentDocument>;
- readonly name: string;
- readonly environmentId: EnvironmentId | null;
- readonly htmlRender: boolean;
- readonly nativeViewer: "pending" | "open" | "unavailable" | null;
- readonly nativeError: string | null;
- readonly onOpenNative: () => void;
-}) {
- const { document } = props;
- if (document.error) {
- return (
- <View className="flex-1 items-center justify-center bg-sheet px-6">
- <EmptyState
- title="File unavailable"
- detail={document.error}
- actionLabel="Try again"
- onAction={document.retry}
- />
- </View>
- );
- }
- if (props.nativeViewer !== null && props.nativeViewer !== "unavailable") {
- return <FilePreviewLoading message="Opening in file viewer..." />;
- }
- if (!document.uri || (document.needsText && !document.content)) {
- return <FilePreviewLoading message="Loading file..." />;
- }
- if (document.needsText && document.content) {
- const { content, table } = document;
- return (
- <View className="flex-1 bg-sheet">
- {content.truncated ? (
- <FilePreviewNotice title="Partial file">
- Preview limited to the first 1 MB. Save or share the file to read it in full.
- </FilePreviewNotice>
- ) : null}
- {table && document.activeMode === "table" ? (
- <DelimitedFilePreview table={table} />
- ) : document.activeMode === "markdown" && props.environmentId ? (
- <FileMarkdownPreview
- cwd=""
- relativePath=""
- environmentId={props.environmentId}
- threadId={null}
- markdown={content.text}
- captured
- />
- ) : (
- <SourceFileSurface contents={content.text} path={props.name} selectable />
- )}
- </View>
- );
- }
- if (document.kind === "audio") {
- return <AudioFilePreview key={document.revision} uri={document.uri} onRetry={document.retry} />;
- }
- if (document.kind === "html") {
- return props.htmlRender ? (
- <HtmlRenderWebView key={document.uri} uri={document.uri} title={props.name} nested={false} />
- ) : (
- <WorkspaceFileWebPreview uri={document.uri} />
- );
- }
- return (
- <View className="flex-1 items-center justify-center bg-sheet px-6">
- <EmptyState
- title="No preview for this file"
- detail={
- props.nativeError ??
- "No app on this device can show this format. Save or share it to open it elsewhere."
- }
- actionLabel="Try again"
- onAction={props.onOpenNative}
- />
- </View>
- );
-}
-
export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
const navigation = useNavigation();
const { appearance, setCodeWordBreak } = useAppearancePreferences();
@@ -284,6 +198,36 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();
};
const subtitle = `${draftKey ? "Draft attachment" : "Attachment"}${sizeBytes > 0 ? ` · ${formatAttachmentSize(sizeBytes)}` : ""}`;
+ const refresh = useRefreshAssetUrl(environmentId, resource);
+ const capabilities = useEnvironmentServerConfig(environmentId)?.environment.capabilities;
+
+ if (document.kind === "archive" && isZipFile(params) && !document.error) {
+ const threadDraftKey =
+ environmentId && params.threadId
+ ? scopedThreadKey(environmentId, ThreadId.make(params.threadId))
+ : null;
+ return (
+ <ZipArchiveView
+ name={params.name}
+ subtitle={subtitle}
+ tintColor={iconColor}
+ sizeBytes={sizeBytes}
+ uri={uri}
+ isLocal={localAttachment !== null}
+ refresh={refresh}
+ environmentId={environmentId}
+ // Entries go to the thread's chat composer, also from a question-answer draft.
+ draftKey={threadDraftKey ?? draftKey}
+ maxAttachmentBytes={
+ capabilities?.attachmentUploads && capabilities.fileAttachments
+ ? clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes)
+ : undefined
+ }
+ onSave={() => void share()}
+ onRemove={draftKey ? removeFromDraft : null}
+ />
+ );
+ }
return (
<View className="flex-1 bg-sheet">
diff --git a/apps/mobile/src/features/files/ZipArchiveView.test.tsx b/apps/mobile/src/features/files/ZipArchiveView.test.tsx
new file mode 100644
index 00000000000..d26b7ecc4f9
--- /dev/null
+++ b/apps/mobile/src/features/files/ZipArchiveView.test.tsx
@@ -0,0 +1,315 @@
+import { AsyncResult } from "effect/reactivity";
+import { act, type ComponentProps, type ReactNode } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, onTestFinished, vi } from "vite-plus/test";
+import type { ServerConfig } from "@t3tools/contracts";
+
+import type { ZipTreeRow } from "./zipTree";
+
+const files = vi.hoisted(() => new Map<string, Uint8Array>());
+const navigation = vi.hoisted(() => ({ remove: null as (() => void) | null }));
+const server = vi.hoisted(() => ({
+ capabilities: { repositoryIdentity: false } as ServerConfig["environment"]["capabilities"],
+ refresh: vi.fn(async () => "file:///first.zip"),
+}));
+
+vi.mock("../../state/entities", () => ({
+ useEnvironmentServerConfig: () => ({ environment: { capabilities: server.capabilities } }),
+}));
+vi.mock("../../state/assets", () => ({
+ useRefreshAssetUrl: () => server.refresh,
+ useFreshAssetUrl: () => AsyncResult.success({ url: "file:///first.zip", authorizedAt: 0 }),
+}));
+
+vi.mock("react-native", () => {
+ const Slot = (props: { readonly children?: ReactNode }) => <div>{props.children}</div>;
+ return {
+ View: Slot,
+ Text: Slot,
+ ScrollView: Slot,
+ ActivityIndicator: () => null,
+ Platform: { OS: "ios" },
+ Keyboard: { dismiss: vi.fn() },
+ Pressable: (props: {
+ readonly children?: ReactNode;
+ readonly accessibilityLabel?: string;
+ readonly disabled?: boolean;
+ readonly onPress?: () => void;
+ }) => (
+ <button
+ aria-label={props.accessibilityLabel}
+ disabled={props.disabled}
+ onClick={props.onPress}
+ >
+ {props.children}
+ </button>
+ ),
+ TextInput: (props: {
+ readonly accessibilityLabel?: string;
+ readonly value: string;
+ readonly onChangeText: (value: string) => void;
+ }) => (
+ <input
+ aria-label={props.accessibilityLabel}
+ value={props.value}
+ onChange={(event) => props.onChangeText(event.target.value)}
+ />
+ ),
+ };
+});
+vi.mock("@legendapp/list/react-native", () => ({
+ LegendList: (props: {
+ readonly data: ZipTreeRow[];
+ readonly ListHeaderComponent: ReactNode;
+ readonly ListEmptyComponent: ReactNode;
+ readonly keyExtractor: (row: ZipTreeRow) => string;
+ readonly renderItem: (input: { item: ZipTreeRow }) => ReactNode;
+ }) => (
+ <div>
+ {props.ListHeaderComponent}
+ {props.data.length === 0 ? props.ListEmptyComponent : null}
+ {props.data.map((item) => (
+ <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
+ ))}
+ </div>
+ ),
+}));
+vi.mock("expo-file-system", () => ({
+ Directory: class {
+ create() {}
+ },
+ Paths: { document: { uri: "file:///documents" } },
+ File: class {
+ constructor(private readonly uri: string) {}
+ get exists() {
+ return false;
+ }
+ get size() {
+ return files.get(this.uri)?.byteLength ?? null;
+ }
+ async arrayBuffer() {
+ const bytes = files.get(this.uri);
+ if (!bytes) throw new Error(`Missing ZIP fixture: ${this.uri}`);
+ return Uint8Array.from(bytes).buffer;
+ }
+ },
+}));
+vi.mock("expo/fetch", () => ({ fetch: vi.fn() }));
+vi.mock("expo-crypto", () => ({ randomUUID: vi.fn() }));
+vi.mock("@react-navigation/native", () => ({
+ useNavigation: () => ({ canGoBack: () => false }),
+ usePreventRemove: (enabled: boolean, remove: () => void) => {
+ navigation.remove = enabled ? remove : null;
+ },
+}));
+vi.mock("react-native-safe-area-context", () => ({
+ useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
+}));
+vi.mock("../../native/NativeScrollViewMarker", () => ({ NativeScrollView: () => null }));
+vi.mock("../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null }));
+vi.mock("../../components/ui/Toolbar", () => {
+ const Slot = (props: { readonly children?: ReactNode }) => <div>{props.children}</div>;
+ return {
+ Toolbar: Object.assign(Slot, {
+ Button: () => null,
+ Menu: Slot,
+ MenuAction: (props: {
+ readonly children?: ReactNode;
+ readonly disabled?: boolean;
+ readonly onPress?: () => void;
+ }) => (
+ <button disabled={props.disabled} onClick={props.onPress}>
+ {props.children}
+ </button>
+ ),
+ }),
+ };
+});
+vi.mock("../../components/ui/AndroidScreenHeader", () => ({ AndroidScreenHeader: () => null }));
+vi.mock("../../components/ui/Menu", () => ({ Menu: () => null }));
+vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
+vi.mock("../../components/ui/Progress", () => ({ Progress: () => null }));
+vi.mock("../../components/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
+vi.mock("../../components/FilePreviewModal", () => ({ FilePreviewModal: () => null }));
+vi.mock("../../lib/copyTextWithHaptic", () => ({}));
+vi.mock("./SourceFileSurface", () => ({
+ SourceFileSurface: (props: { readonly contents: string }) => <pre>{props.contents}</pre>,
+}));
+vi.mock("./AudioFilePreview", () => ({ AudioFilePreview: () => null }));
+vi.mock("./FileMarkdownPreview", () => ({ FileMarkdownPreview: () => null }));
+vi.mock("./WorkspaceFileWebPreview", () => ({ WorkspaceFileWebPreview: () => null }));
+vi.mock("../threads/HtmlRenderWebView", () => ({ HtmlRenderWebView: () => null }));
+vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
+ useAppearancePreferences: () => ({
+ appearance: { codeWordBreak: false },
+ themeVariables: { "--color-icon": "#000000" },
+ setCodeWordBreak: () => {},
+ }),
+}));
+
+import { ZipArchiveView } from "./ZipArchiveView";
+import { AttachmentFileScreen } from "./AttachmentFileScreen";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { composerDraftsAtom } from "../../state/use-composer-drafts";
+
+function setup() {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ vi.useFakeTimers({ toFake: ["setImmediate", "clearImmediate"] });
+ files.clear();
+ navigation.remove = null;
+ server.capabilities = { repositoryIdentity: false };
+ server.refresh.mockClear();
+ appAtomRegistry.set(composerDraftsAtom, {});
+ files.set(
+ "file:///first.zip",
+ Uint8Array.from(
+ atob(
+ "UEsDBBQAAAAAAAAAIVyzyFShFgAAABYAAAAJAAAAZmlyc3QudHh0Rmlyc3QgYXJjaGl2ZSBjb250ZW50c1BLAQIUAxQAAAAAAAAAIVyzyFShFgAAABYAAAAJAAAAAAAAAAAAAACAAQAAAABmaXJzdC50eHRQSwUGAAAAAAEAAQA3AAAAPQAAAAAA",
+ ),
+ (character) => character.charCodeAt(0),
+ ),
+ );
+
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ onTestFinished(() => {
+ act(() => root.unmount());
+ files.clear();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+ const props: ComponentProps<typeof ZipArchiveView> = {
+ name: "archive.zip",
+ subtitle: "ZIP",
+ tintColor: "#000000",
+ sizeBytes: 0,
+ uri: "file:///first.zip",
+ isLocal: true,
+ refresh: async () => null,
+ environmentId: null,
+ draftKey: null,
+ maxAttachmentBytes: undefined,
+ onSave: () => {},
+ onRemove: null,
+ };
+ return {
+ container,
+ root,
+ props,
+ render: async (input = props) => {
+ await act(async () => root.render(<ZipArchiveView {...input} />));
+ },
+ settle: async (assert: () => void) => {
+ await act(async () => vi.runAllTimersAsync());
+ assert();
+ },
+ };
+}
+
+it("opens a ZIP chat attachment as a browsable archive on the attachment file screen", async () => {
+ const screen = setup();
+ server.capabilities = {
+ repositoryIdentity: false,
+ attachmentUploads: true,
+ fileAttachments: { maxUploadBytes: 1024 },
+ };
+ const { fetch } = await import("expo/fetch");
+ vi.mocked(fetch, { partial: true }).mockImplementation(async () => ({
+ ok: true,
+ body: new Response(Uint8Array.from(files.get("file:///first.zip")!)).body,
+ }));
+ await act(async () =>
+ screen.root.render(
+ <AttachmentFileScreen
+ route={{
+ params: {
+ environmentId: "environment-1",
+ threadId: "thread-1",
+ attachmentId: "attachment-1",
+ name: "archive.zip",
+ mimeType: "application/zip",
+ sizeBytes: "200",
+ },
+ }}
+ />,
+ ),
+ );
+ await screen.settle(() =>
+ expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull(),
+ );
+ await act(async () =>
+ screen.container.querySelector<HTMLButtonElement>('[aria-label="first.txt"]')!.click(),
+ );
+ await screen.settle(() =>
+ expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
+ );
+ const add = Array.from(screen.container.querySelectorAll("button")).find(
+ (button) => button.textContent === "Add to chat",
+ );
+ expect(add?.disabled).toBe(false);
+});
+
+it("keeps the ZIP filter and archive open when native Back closes a selected entry", async () => {
+ const screen = setup();
+ await screen.render();
+ await screen.settle(() =>
+ expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull(),
+ );
+ const filter = screen.container.querySelector<HTMLInputElement>(
+ '[aria-label="Filter files in ZIP"]',
+ )!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(
+ filter,
+ "first",
+ );
+ filter.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await act(async () =>
+ screen.container.querySelector<HTMLButtonElement>('[aria-label="first.txt"]')!.click(),
+ );
+ await screen.settle(() =>
+ expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
+ );
+
+ expect(navigation.remove).not.toBeNull();
+ await act(async () => navigation.remove!());
+
+ expect(screen.container.querySelector("pre")).toBeNull();
+ expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull();
+ expect(
+ screen.container.querySelector<HTMLInputElement>('[aria-label="Filter files in ZIP"]')?.value,
+ ).toBe("first");
+});
+
+it("explains why an encrypted ZIP cannot be browsed", async () => {
+ const screen = setup();
+ const bytes = files.get("file:///first.zip")!;
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const directory = view.getUint32(bytes.length - 6, true);
+ view.setUint16(directory + 8, view.getUint16(directory + 8, true) | 1, true);
+ await screen.render();
+ await screen.settle(() => expect(screen.container.textContent).toContain("Encrypted zip"));
+ expect(screen.container.querySelector('[aria-label="first.txt"]')).toBeNull();
+});
+
+it("keeps the archive and selected entry when the parent re-renders with a new refresh", async () => {
+ const screen = setup();
+ await screen.render();
+ await screen.settle(() =>
+ expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull(),
+ );
+ await act(async () =>
+ screen.container.querySelector<HTMLButtonElement>('[aria-label="first.txt"]')!.click(),
+ );
+ await screen.settle(() =>
+ expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
+ );
+ files.delete("file:///first.zip");
+
+ await screen.render({ ...screen.props, refresh: async () => null });
+ await screen.settle(() =>
+ expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
+ );
+ expect(navigation.remove).not.toBeNull();
+});
diff --git a/apps/mobile/src/features/files/ZipArchiveView.tsx b/apps/mobile/src/features/files/ZipArchiveView.tsx
new file mode 100644
index 00000000000..537b9c736f6
--- /dev/null
+++ b/apps/mobile/src/features/files/ZipArchiveView.tsx
@@ -0,0 +1,870 @@
+import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
+import {
+ ARCHIVE_ENTRY_MAX_BYTES,
+ ARCHIVE_MAX_BYTES,
+ boundedZip,
+} from "@t3tools/client-runtime/zip/bounded-zip";
+import type { EnvironmentId } from "@t3tools/contracts";
+import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
+import {
+ decodeFilePreviewText,
+ filePreviewKind,
+ hostPreviewMimeTypeFromExtension,
+} from "@t3tools/shared/filePreview";
+import { LegendList } from "@legendapp/list/react-native";
+import { fetch } from "expo/fetch";
+import { File } from "expo-file-system";
+import { useNavigation, usePreventRemove } from "@react-navigation/native";
+import { useEffect, useEffectEvent, useRef, useState } from "react";
+import { Keyboard, Platform, Pressable, ScrollView, TextInput, View } from "react-native";
+import { useSafeAreaInsets } from "react-native-safe-area-context";
+
+import { PierreEntryIcon } from "../../components/PierreEntryIcon";
+import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
+import { SymbolView } from "../../components/ui/AppSymbol";
+import { AppText as Text } from "../../components/ui/AppText";
+import { Button } from "../../components/ui/Button";
+import { EmptyState } from "../../components/ui/EmptyState";
+import { Progress } from "../../components/ui/Progress";
+import { Toolbar } from "../../components/ui/Toolbar";
+import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
+import { NativeScrollView } from "../../native/NativeScrollViewMarker";
+import { NativeStackScreenOptions } from "../../native/StackHeader";
+import * as Dialog from "../../components/ui/Dialog";
+import { FilePreviewModal } from "../../components/FilePreviewModal";
+import {
+ nativeViewerErrorMessage,
+ shareGeneratedAttachment,
+ writeGeneratedAttachmentFile,
+} from "../../lib/attachmentDownload";
+import { attachmentDocumentPresentation } from "../../lib/attachmentDocumentPresentation";
+import {
+ createComposerFileAttachment,
+ removePersistedComposerAttachmentFile,
+} from "../../lib/composerImages";
+import { appendComposerDraftAttachments } from "../../state/use-composer-drafts";
+import { AttachmentDocumentBody, nativeViewerKind } from "./AttachmentDocumentBody";
+import { FilePreviewLoading } from "./FilePreviewFeedback";
+import {
+ buildZipTree,
+ flattenZipTree,
+ zipDownloadTimeLeft,
+ zipFolderLabel,
+ type ZipEntry,
+ type ZipTreeRow,
+} from "./zipTree";
+
+export function isZipFile(file: { readonly name: string; readonly mimeType: string }) {
+ const mime = file.mimeType.split(";", 1)[0]?.trim().toLowerCase();
+ return (
+ mime === "application/zip" ||
+ mime === "application/x-zip-compressed" ||
+ file.name.toLowerCase().endsWith(".zip")
+ );
+}
+
+interface ZipArchive {
+ readonly entries: ReadonlyArray<ZipEntry>;
+ readonly fileCount: number;
+}
+
+interface ZipFailure {
+ readonly title: string;
+ readonly detail: string;
+ readonly retry: boolean;
+}
+
+const SAVE_ZIP_HINT = "Save the ZIP to open it in another app.";
+const TOO_LARGE: ZipFailure = {
+ title: "Too large to browse here",
+ detail: `Browsing works up to ${formatAttachmentSize(ARCHIVE_MAX_BYTES)}. ${SAVE_ZIP_HINT}`,
+ retry: false,
+};
+const CANCELLED: ZipFailure = {
+ title: "Download cancelled",
+ detail: "The ZIP wasn't downloaded. Try again to list its files.",
+ retry: true,
+};
+const NETWORK: ZipFailure = {
+ title: "Couldn't download this ZIP",
+ detail: "Check the connection to this environment and try again.",
+ retry: true,
+};
+
+class ZipFailureError extends Error {
+ constructor(readonly failure: ZipFailure) {
+ super(failure.title);
+ }
+}
+
+function errorMessage(cause: unknown, fallback: string) {
+ return cause instanceof Error ? cause.message : fallback;
+}
+
+async function readArchiveBody(
+ body: ReadableStream<Uint8Array>,
+ onProgress: (receivedBytes: number) => void,
+) {
+ const reader = body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ try {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
+ chunks.push(value);
+ onProgress(size);
+ }
+ } finally {
+ void reader.cancel().catch(() => {});
+ }
+ const bytes = new Uint8Array(size);
+ let offset = 0;
+ for (const chunk of chunks) {
+ bytes.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+ return bytes.buffer;
+}
+
+async function openArchive(bytes: ArrayBuffer): Promise<ZipArchive> {
+ let files: Awaited<ReturnType<typeof boundedZip>>;
+ try {
+ files = await boundedZip(bytes);
+ } catch (cause) {
+ throw new ZipFailureError({
+ title: "Couldn't browse this ZIP",
+ detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`,
+ retry: false,
+ });
+ }
+ const entries = [...files].map(([path, file]): ZipEntry => {
+ const name = path.split("/").findLast(Boolean) ?? path;
+ const dot = name.lastIndexOf(".");
+ return {
+ path,
+ name,
+ isDirectory: file.directory,
+ sizeBytes: file.bytes.byteLength,
+ mimeType:
+ (dot > 0 ? hostPreviewMimeTypeFromExtension(name.slice(dot).toLowerCase()) : null) ??
+ "application/octet-stream",
+ bytes: file.bytes,
+ };
+ });
+ return { entries, fileCount: entries.filter((entry) => !entry.isDirectory).length };
+}
+
+type ArchiveState =
+ | { readonly status: "loading"; readonly receivedBytes: number; readonly timeLeft: string | null }
+ | { readonly status: "ready"; readonly archive: ZipArchive }
+ | { readonly status: "failed"; readonly failure: ZipFailure };
+
+function useZipArchive(input: {
+ readonly uri: string | null;
+ readonly isLocal: boolean;
+ readonly sizeBytes: number;
+ readonly refresh: () => Promise<string | null>;
+}) {
+ const [state, setState] = useState<ArchiveState>({
+ status: "loading",
+ receivedBytes: 0,
+ timeLeft: null,
+ });
+ const [revision, setRevision] = useState(0);
+ const controller = useRef<AbortController | null>(null);
+ const { uri, isLocal, sizeBytes } = input;
+ // The parent mints a new refresh callback on every render; it must not reload the archive.
+ const refresh = useEffectEvent(input.refresh);
+ // oxlint-disable-next-line t3code/react-effect-budget -- Load archive bytes and cancel the stream on cleanup.
+ useEffect(() => {
+ if (!uri) return;
+ const abort = new AbortController();
+ controller.current = abort;
+ const startedAt = Date.now();
+ // oxlint-disable-next-line react/set-state-in-effect -- A new archive load resets its progress.
+ setState({ status: "loading", receivedBytes: 0, timeLeft: null });
+ void (async () => {
+ if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
+ if (isLocal) {
+ const file = new File(uri);
+ if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
+ return openArchive(await file.arrayBuffer());
+ }
+ const url = (await refresh()) ?? uri;
+ const response = await fetch(url, { signal: abort.signal });
+ if (!response.ok || !response.body) throw new ZipFailureError(NETWORK);
+ const bytes = await readArchiveBody(response.body, (receivedBytes) =>
+ setState({
+ status: "loading",
+ receivedBytes,
+ timeLeft: zipDownloadTimeLeft({
+ receivedBytes,
+ totalBytes: sizeBytes,
+ elapsedMs: Date.now() - startedAt,
+ }),
+ }),
+ );
+ abort.signal.throwIfAborted();
+ return openArchive(bytes);
+ })()
+ .then((archive) => {
+ if (!abort.signal.aborted) setState({ status: "ready", archive });
+ })
+ .catch((cause: unknown) => {
+ if (!abort.signal.aborted)
+ setState({
+ status: "failed",
+ failure: cause instanceof ZipFailureError ? cause.failure : NETWORK,
+ });
+ });
+ return () => abort.abort();
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reload the archive.
+ }, [uri, isLocal, sizeBytes, revision]);
+ return {
+ state,
+ retry: () => setRevision((value) => value + 1),
+ cancel: () => {
+ controller.current?.abort();
+ setState({ status: "failed", failure: CANCELLED });
+ },
+ };
+}
+
+function ZipTreeRowView(props: {
+ readonly row: ZipTreeRow;
+ readonly collapsed: boolean;
+ readonly onToggle: (path: string) => void;
+ readonly onOpen: (entry: ZipEntry) => void;
+}) {
+ const { node, depth } = props.row;
+ const entry = node.entry;
+ const folder = entry ? null : zipFolderLabel(node.label);
+ return (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={entry ? entry.path : `${node.path} folder`}
+ accessibilityState={entry ? undefined : { expanded: !props.collapsed }}
+ onPress={() => (entry ? props.onOpen(entry) : props.onToggle(node.path))}
+ className="mx-2 h-11 flex-row items-center gap-1.5 rounded-lg pr-2.5 active:bg-subtle"
+ style={{ paddingLeft: 8 + depth * 18 }}
+ >
+ <View className="w-4 items-center">
+ {entry ? null : (
+ <SymbolView
+ name={props.collapsed ? "chevron.right" : "chevron.down"}
+ size={12}
+ tintColorClassName="accent-icon-muted"
+ type="monochrome"
+ />
+ )}
+ </View>
+ <View className="w-5 items-center">
+ <PierreEntryIcon path={node.path} kind={entry ? "file" : "directory"} size={17} />
+ </View>
+ <Text className="min-w-0 flex-1 text-[15px] text-foreground" numberOfLines={1}>
+ {folder ? (
+ <>
+ <Text className="text-[15px] text-foreground-muted">{folder.prefix}</Text>
+ {folder.name}
+ </>
+ ) : (
+ node.label
+ )}
+ </Text>
+ <Text className="text-xs text-foreground-muted">
+ {entry
+ ? formatAttachmentSize(entry.sizeBytes)
+ : props.collapsed
+ ? `${node.fileCount} ${node.fileCount === 1 ? "file" : "files"}`
+ : ""}
+ </Text>
+ </Pressable>
+ );
+}
+
+function ZipArchiveHeader(props: {
+ readonly name: string;
+ readonly subtitle: string;
+ readonly tintColor: string;
+ readonly onSave: () => void;
+ readonly onRemove: (() => void) | null;
+}) {
+ const navigation = useNavigation();
+ const isAndroid = Platform.OS === "android";
+ return (
+ <>
+ <NativeStackScreenOptions
+ options={{
+ headerShown: !isAndroid,
+ headerTintColor: props.tintColor,
+ headerTitle: props.name,
+ title: props.name,
+ unstable_headerSubtitle: isAndroid ? undefined : props.subtitle,
+ }}
+ />
+ {isAndroid ? (
+ <AndroidScreenHeader
+ title={props.name}
+ subtitle={props.subtitle}
+ onBack={() => {
+ if (navigation.canGoBack()) navigation.goBack();
+ }}
+ actions={[
+ { accessibilityLabel: "Save ZIP", icon: "square.and.arrow.up", onPress: props.onSave },
+ ...(props.onRemove
+ ? [
+ {
+ accessibilityLabel: "Remove from draft",
+ icon: "trash" as const,
+ onPress: props.onRemove,
+ destructive: true,
+ overflowOnly: true,
+ },
+ ]
+ : []),
+ ]}
+ />
+ ) : (
+ <Toolbar placement="right">
+ {props.onRemove ? (
+ <Toolbar.Menu accessibilityLabel="ZIP actions" icon="ellipsis">
+ <Toolbar.MenuAction icon="square.and.arrow.up" onPress={props.onSave}>
+ Save ZIP
+ </Toolbar.MenuAction>
+ <Toolbar.MenuAction icon="trash" destructive onPress={props.onRemove}>
+ Remove from draft
+ </Toolbar.MenuAction>
+ </Toolbar.Menu>
+ ) : (
+ <Toolbar.Button
+ accessibilityLabel="Save ZIP"
+ icon="square.and.arrow.up"
+ onPress={props.onSave}
+ />
+ )}
+ </Toolbar>
+ )}
+ </>
+ );
+}
+
+function ZipArchiveProgress(props: {
+ readonly receivedBytes: number;
+ readonly totalBytes: number;
+ readonly timeLeft: string | null;
+ readonly onCancel: () => void;
+}) {
+ const { timeLeft } = props;
+ return (
+ <View className="flex-1 justify-center gap-3 bg-sheet px-8">
+ <Text className="text-xl font-t3-semibold text-foreground">
+ {formatAttachmentSize(props.receivedBytes)}
+ {props.totalBytes > 0 ? (
+ <Text className="text-xl text-foreground-muted">
+ {` of ${formatAttachmentSize(props.totalBytes)}`}
+ </Text>
+ ) : null}
+ </Text>
+ <Progress
+ value={props.totalBytes > 0 ? props.receivedBytes / props.totalBytes : undefined}
+ label="ZIP download progress"
+ />
+ <Text className="text-sm text-foreground-muted">
+ {`Downloading the ZIP so its files can be listed.${timeLeft ? ` ${timeLeft} on this connection.` : ""}`}
+ </Text>
+ <Button label="Cancel" onPress={props.onCancel} />
+ </View>
+ );
+}
+
+function ZipArchiveFailure(props: {
+ readonly failure: ZipFailure;
+ readonly onRetry: () => void;
+ readonly onSave: () => void;
+}) {
+ return (
+ <View className="flex-1 items-center justify-center bg-sheet px-6">
+ <EmptyState
+ variant="plain"
+ title={props.failure.title}
+ detail={props.failure.detail}
+ action={
+ <View className="flex-row gap-3">
+ {props.failure.retry ? (
+ <Button tone="primary" label="Try again" onPress={props.onRetry} />
+ ) : null}
+ <Button
+ tone={props.failure.retry ? "secondary" : "primary"}
+ label="Save ZIP"
+ onPress={props.onSave}
+ />
+ </View>
+ }
+ />
+ </View>
+ );
+}
+
+function ZipArchiveList(props: {
+ readonly archive: ZipArchive;
+ readonly headerInset: number;
+ readonly onOpen: (entry: ZipEntry) => void;
+}) {
+ const [query, setQuery] = useState("");
+ const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
+ const { archive } = props;
+ const rows = flattenZipTree(buildZipTree(archive.entries), collapsed, query);
+ const toggle = (path: string) =>
+ setCollapsed((current) => {
+ const next = new Set(current);
+ if (!next.delete(path)) next.add(path);
+ return next;
+ });
+ const fileCount = archive.fileCount;
+ return (
+ <View className="flex-1 bg-sheet">
+ <LegendList
+ renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
+ contentInsetStartAdjustment={props.headerInset}
+ className="flex-1"
+ data={rows}
+ keyExtractor={(row) => `${row.node.entry ? "f" : "d"}:${row.node.path}`}
+ contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
+ automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
+ estimatedItemSize={44}
+ recycleItems
+ keyboardDismissMode="on-drag"
+ keyboardShouldPersistTaps="handled"
+ extraData={collapsed}
+ contentContainerStyle={{ paddingBottom: 4 }}
+ ListHeaderComponent={
+ <View className="px-4 pt-3 pb-2.5">
+ <View className="h-[38px] flex-row items-center gap-2 rounded-[10px] bg-subtle px-3">
+ <SymbolView name="magnifyingglass" size={15} tintColorClassName="accent-icon-muted" />
+ <TextInput
+ accessibilityLabel="Filter files in ZIP"
+ autoCapitalize="none"
+ autoCorrect={false}
+ placeholder={`Filter ${fileCount} ${fileCount === 1 ? "file" : "files"}`}
+ placeholderTextColorClassName="accent-placeholder"
+ cursorColorClassName="accent-focus"
+ className="min-w-0 flex-1 font-sans text-[15px] text-foreground"
+ value={query}
+ onChangeText={setQuery}
+ />
+ {query ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel="Clear filter"
+ hitSlop={10}
+ onPress={() => setQuery("")}
+ >
+ <SymbolView
+ name="xmark.circle.fill"
+ size={16}
+ tintColorClassName="accent-icon-muted"
+ />
+ </Pressable>
+ ) : null}
+ </View>
+ </View>
+ }
+ renderItem={({ item }) => (
+ <ZipTreeRowView
+ row={item}
+ collapsed={collapsed.has(item.node.path)}
+ onToggle={toggle}
+ onOpen={props.onOpen}
+ />
+ )}
+ ListEmptyComponent={
+ query ? (
+ <EmptyState
+ variant="plain"
+ title={`No files match “${query.trim()}”`}
+ detail="The filter checks file names and folder paths."
+ action={<Button label="Clear filter" onPress={() => setQuery("")} />}
+ />
+ ) : (
+ <EmptyState variant="plain" title="This ZIP is empty" detail="It has no files." />
+ )
+ }
+ />
+ </View>
+ );
+}
+
+export function ZipArchiveView(props: {
+ readonly name: string;
+ readonly subtitle: string;
+ readonly tintColor: string;
+ readonly sizeBytes: number;
+ readonly uri: string | null;
+ readonly isLocal: boolean;
+ readonly refresh: () => Promise<string | null>;
+ readonly environmentId: EnvironmentId | null;
+ readonly draftKey: string | null;
+ readonly maxAttachmentBytes: number | undefined;
+ readonly onSave: () => void;
+ readonly onRemove: (() => void) | null;
+}) {
+ const { state, retry, cancel } = useZipArchive(props);
+ const [selection, setSelection] = useState<{
+ readonly archive: ZipArchive;
+ readonly entry: ZipEntry;
+ } | null>(null);
+ const archive = state.status === "ready" ? state.archive : null;
+ const selected = selection && selection.archive === archive ? selection.entry : null;
+ const entryOpen = selected !== null;
+ usePreventRemove(entryOpen, () => setSelection(null));
+ const insets = useSafeAreaInsets();
+ const columnMetrics = useNativeColumnLayoutMetrics();
+ const headerInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
+ return (
+ <View className="flex-1 bg-sheet">
+ {entryOpen ? null : (
+ <ZipArchiveHeader
+ name={props.name}
+ subtitle={
+ archive
+ ? `${archive.fileCount} ${archive.fileCount === 1 ? "file" : "files"}${props.sizeBytes > 0 ? ` · ${formatAttachmentSize(props.sizeBytes)}` : ""}`
+ : props.subtitle
+ }
+ tintColor={props.tintColor}
+ onSave={props.onSave}
+ onRemove={props.onRemove}
+ />
+ )}
+ {state.status === "ready" ? (
+ <ZipArchiveList
+ archive={state.archive}
+ headerInset={headerInset}
+ onOpen={(entry) => {
+ Keyboard.dismiss();
+ setSelection({ archive: state.archive, entry });
+ }}
+ />
+ ) : (
+ <View className="flex-1" style={{ paddingTop: headerInset }}>
+ {state.status === "loading" ? (
+ props.isLocal || state.receivedBytes === 0 ? (
+ <FilePreviewLoading message="Opening ZIP..." />
+ ) : (
+ <ZipArchiveProgress
+ receivedBytes={state.receivedBytes}
+ totalBytes={props.sizeBytes}
+ timeLeft={state.timeLeft}
+ onCancel={cancel}
+ />
+ )
+ ) : (
+ <ZipArchiveFailure failure={state.failure} onRetry={retry} onSave={props.onSave} />
+ )}
+ </View>
+ )}
+ {selected ? (
+ <View className="absolute inset-0">
+ <ZipEntryView
+ key={selected.path}
+ archiveName={props.name}
+ entry={selected}
+ environmentId={props.environmentId}
+ draftKey={props.draftKey}
+ maxAttachmentBytes={props.maxAttachmentBytes}
+ onBack={() => setSelection(null)}
+ />
+ </View>
+ ) : null}
+ </View>
+ );
+}
+
+async function addZipEntryToDraft(input: {
+ readonly entry: ZipEntry;
+ readonly draftKey: string;
+ readonly maxBytes: number;
+ readonly signal: AbortSignal;
+}) {
+ const { entry, signal } = input;
+ const file = await writeGeneratedAttachmentFile({
+ bytes: entry.bytes,
+ attachment: { name: entry.name, mimeType: entry.mimeType },
+ });
+ try {
+ signal.throwIfAborted();
+ const attachment = await createComposerFileAttachment({
+ uri: file.uri,
+ name: entry.name,
+ mimeType: entry.mimeType,
+ sizeBytes: entry.sizeBytes,
+ maxBytes: input.maxBytes,
+ });
+ if (signal.aborted) {
+ await removePersistedComposerAttachmentFile(attachment.fileUri);
+ signal.throwIfAborted();
+ }
+ // Rejected attachments are cleaned up by the draft store.
+ if (appendComposerDraftAttachments(input.draftKey, [attachment], { appendReference: true }))
+ throw new Error("This message already has as many attachments as it can hold.");
+ } finally {
+ file.dispose();
+ }
+}
+
+type EntryContent =
+ | { readonly status: "loading" }
+ | { readonly status: "text"; readonly text: string; readonly truncated: boolean }
+ | { readonly status: "file"; readonly uri: string }
+ | { readonly status: "failed"; readonly title: string; readonly message: string };
+
+function ZipEntryView(props: {
+ readonly archiveName: string;
+ readonly entry: ZipEntry;
+ readonly environmentId: EnvironmentId | null;
+ readonly draftKey: string | null;
+ readonly maxAttachmentBytes: number | undefined;
+ readonly onBack: () => void;
+}) {
+ const { entry, draftKey, maxAttachmentBytes } = props;
+ const { mimeType } = entry;
+ const previewKind = filePreviewKind({ name: entry.name, mimeType });
+ const isText = previewKind === "text" || previewKind === "markdown" || previewKind === "html";
+ // Archive HTML is shown as source: a rendered page could load its sibling files.
+ const kind = previewKind === "html" ? "text" : previewKind;
+ const viewerKind = isText || kind === "audio" ? null : (nativeViewerKind(kind) ?? "document");
+ const tooBig = entry.sizeBytes > ARCHIVE_ENTRY_MAX_BYTES;
+ const [content, setContent] = useState<EntryContent>(
+ tooBig
+ ? {
+ status: "failed",
+ title: "Too big to preview",
+ message: `Previews stop at ${formatAttachmentSize(ARCHIVE_ENTRY_MAX_BYTES)}. Save the file to open it in another app.`,
+ }
+ : { status: "loading" },
+ );
+ const [rendered, setRendered] = useState(true);
+ const [revision, setRevision] = useState(0);
+ const [viewerOpen, setViewerOpen] = useState(true);
+ const [viewerError, setViewerError] = useState<string | null>(null);
+ const [busy, setBusy] = useState<"save" | "attach" | null>(null);
+ const action = useRef<AbortController | null>(null);
+ const pendingViewerError = useRef<string | null>(null);
+ // oxlint-disable-next-line t3code/react-effect-budget -- Cancel a pending save or attach when the entry closes.
+ useEffect(() => () => action.current?.abort(), []);
+ // oxlint-disable-next-line t3code/react-effect-budget -- Write the selected entry to a cached file and release it on cleanup.
+ useEffect(() => {
+ if (tooBig) return;
+ const controller = new AbortController();
+ let release: (() => void) | undefined;
+ void (async (): Promise<EntryContent> => {
+ if (isText) return { status: "text", ...decodeFilePreviewText(entry.bytes) };
+ const file = await writeGeneratedAttachmentFile({
+ bytes: entry.bytes,
+ attachment: { name: entry.name, mimeType },
+ });
+ if (controller.signal.aborted) {
+ file.dispose();
+ controller.signal.throwIfAborted();
+ }
+ release = file.dispose;
+ return { status: "file", uri: file.uri };
+ })()
+ .then((value) => {
+ if (!controller.signal.aborted) setContent(value);
+ })
+ .catch((cause: unknown) => {
+ if (!controller.signal.aborted)
+ setContent({
+ status: "failed",
+ title: "Couldn't read this file",
+ message: errorMessage(cause, "Could not read this file."),
+ });
+ });
+ return () => {
+ controller.abort();
+ release?.();
+ };
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reread the entry.
+ }, [entry, isText, mimeType, tooBig, revision]);
+
+ const run = (kind: "save" | "attach", task: (signal: AbortSignal) => Promise<unknown>) => {
+ if (busy) return;
+ setBusy(kind);
+ const controller = new AbortController();
+ action.current = controller;
+ void task(controller.signal).then(
+ () => {
+ if (controller.signal.aborted) return;
+ setBusy(null);
+ if (kind === "attach")
+ Dialog.alert("Added to chat", `${entry.name} is attached to your message.`);
+ },
+ (cause: unknown) => {
+ if (controller.signal.aborted) return;
+ setBusy(null);
+ Dialog.alert(
+ kind === "save" ? "Could not save file" : "Could not add file to chat",
+ errorMessage(cause, "Please try again."),
+ );
+ },
+ );
+ };
+ const save = () =>
+ run("save", (signal) =>
+ shareGeneratedAttachment({
+ bytes: entry.bytes,
+ attachment: { name: entry.name, mimeType },
+ signal,
+ }),
+ );
+ const canAddToChat = draftKey !== null && maxAttachmentBytes !== undefined;
+ const addToChat = () => {
+ if (draftKey === null || maxAttachmentBytes === undefined) return;
+ run("attach", (signal) =>
+ addZipEntryToDraft({ entry, draftKey, maxBytes: maxAttachmentBytes, signal }),
+ );
+ };
+ const openViewer = () => {
+ setViewerError(null);
+ setViewerOpen(true);
+ };
+
+ const text = content.status === "text" ? content : null;
+ const delimiter = filePreviewDelimiter({ name: entry.name, mimeType });
+ const table = text && delimiter ? parseDelimitedPreview(text.text, delimiter) : null;
+ const uri = content.status === "file" ? content.uri : null;
+ const { renderedMode, activeMode } = attachmentDocumentPresentation({
+ kind,
+ hasTable: table !== null,
+ hasEnvironment: props.environmentId !== null,
+ rendered,
+ });
+ const folders = entry.path.split("/").slice(0, -1);
+ const subtitle = `${[props.archiveName, ...folders].join(" / ")} · ${formatAttachmentSize(entry.sizeBytes)}`;
+ const isAndroid = Platform.OS === "android";
+ return (
+ <View className="flex-1 bg-sheet">
+ <NativeStackScreenOptions
+ options={{
+ headerShown: !isAndroid,
+ headerTitle: entry.name,
+ title: entry.name,
+ unstable_headerSubtitle: isAndroid ? undefined : subtitle,
+ }}
+ />
+ {isAndroid ? (
+ <AndroidScreenHeader
+ title={entry.name}
+ subtitle={subtitle}
+ onBack={props.onBack}
+ actions={[
+ ...(renderedMode
+ ? [
+ {
+ accessibilityLabel: rendered ? "Show source" : "Show preview",
+ icon: rendered ? ("doc.text" as const) : ("eye" as const),
+ onPress: () => setRendered((value) => !value),
+ },
+ ]
+ : []),
+ ...(canAddToChat
+ ? [
+ {
+ accessibilityLabel: "Add to chat",
+ icon: "plus.bubble" as const,
+ onPress: addToChat,
+ disabled: busy !== null,
+ },
+ ]
+ : []),
+ {
+ accessibilityLabel: "Save file",
+ icon: "square.and.arrow.up",
+ onPress: save,
+ loading: busy === "save",
+ },
+ ]}
+ />
+ ) : (
+ <Toolbar placement="right">
+ <Toolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
+ {renderedMode ? (
+ <Toolbar.MenuAction
+ icon={rendered ? "doc.text" : "eye"}
+ onPress={() => setRendered((value) => !value)}
+ >
+ {rendered ? "Show source" : "Show preview"}
+ </Toolbar.MenuAction>
+ ) : null}
+ {canAddToChat ? (
+ <Toolbar.MenuAction icon="plus.bubble" disabled={busy !== null} onPress={addToChat}>
+ Add to chat
+ </Toolbar.MenuAction>
+ ) : null}
+ <Toolbar.MenuAction icon="square.and.arrow.up" disabled={busy !== null} onPress={save}>
+ Save file
+ </Toolbar.MenuAction>
+ </Toolbar.Menu>
+ </Toolbar>
+ )}
+ {content.status === "failed" ? (
+ <ScrollView contentContainerClassName="flex-grow items-center justify-center px-6">
+ <EmptyState
+ variant="plain"
+ title={content.title}
+ detail={content.message}
+ action={
+ <Button tone="primary" label="Save file" loading={busy === "save"} onPress={save} />
+ }
+ />
+ </ScrollView>
+ ) : viewerKind && uri && !viewerOpen ? (
+ // Closing the viewer stays here so Save and Add to chat remain reachable.
+ <View className="flex-1 items-center justify-center bg-sheet px-6">
+ <EmptyState
+ title={viewerError ? "No preview for this file" : entry.name}
+ detail={viewerError ?? "Open it in the file viewer, save it, or add it to chat."}
+ actionLabel="Open in file viewer"
+ onAction={openViewer}
+ />
+ </View>
+ ) : (
+ <AttachmentDocumentBody
+ document={{
+ kind,
+ activeMode,
+ uri,
+ content: text,
+ table,
+ error: null,
+ needsText: isText,
+ retry: () => setRevision((value) => value + 1),
+ revision,
+ }}
+ name={entry.name}
+ environmentId={props.environmentId}
+ htmlRender={false}
+ nativeViewer={viewerKind ? (uri ? "open" : "pending") : null}
+ nativeError={null}
+ onOpenNative={openViewer}
+ />
+ )}
+ {viewerKind && uri && viewerOpen ? (
+ <FilePreviewModal
+ source={{ kind: viewerKind, name: entry.name, mimeType, uri }}
+ onOpenError={(error) => {
+ pendingViewerError.current = nativeViewerErrorMessage(error);
+ }}
+ onRequestClose={() => {
+ setViewerError(pendingViewerError.current);
+ pendingViewerError.current = null;
+ setViewerOpen(false);
+ }}
+ />
+ ) : null}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/files/zipTree.ts b/apps/mobile/src/features/files/zipTree.ts
new file mode 100644
index 00000000000..dcc9552c5c1
--- /dev/null
+++ b/apps/mobile/src/features/files/zipTree.ts
@@ -0,0 +1,139 @@
+export interface ZipEntry {
+ readonly path: string;
+ readonly name: string;
+ readonly isDirectory: boolean;
+ readonly sizeBytes: number;
+ readonly mimeType: string;
+ readonly bytes: Uint8Array<ArrayBuffer>;
+}
+
+export interface ZipTreeNode {
+ readonly path: string;
+ readonly label: string;
+ readonly entry: ZipEntry | null;
+ readonly children: ReadonlyArray<ZipTreeNode>;
+ readonly fileCount: number;
+}
+
+export interface ZipTreeRow {
+ readonly node: ZipTreeNode;
+ readonly depth: number;
+}
+
+interface MutableNode {
+ path: string;
+ name: string;
+ entry: ZipEntry | null;
+ children: Map<string, MutableNode>;
+}
+
+const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
+
+function freeze(node: MutableNode): ZipTreeNode {
+ let current = node;
+ let label = node.name;
+ while (current.path !== "" && current.entry === null && current.children.size === 1) {
+ const [only] = current.children.values();
+ if (!only || only.entry !== null) break;
+ current = only;
+ label = `${label}/${only.name}`;
+ }
+ const children = [...current.children.values()]
+ .sort((left, right) =>
+ (left.entry === null) !== (right.entry === null)
+ ? left.entry === null
+ ? -1
+ : 1
+ : collator.compare(left.name, right.name),
+ )
+ .map(freeze);
+ return {
+ path: current.path,
+ label,
+ entry: current.entry,
+ children,
+ fileCount:
+ current.entry === null ? children.reduce((sum, child) => sum + child.fileCount, 0) : 1,
+ };
+}
+
+export function buildZipTree(entries: ReadonlyArray<ZipEntry>): ReadonlyArray<ZipTreeNode> {
+ const root: MutableNode = { path: "", name: "", entry: null, children: new Map() };
+ for (const entry of entries) {
+ const parts = entry.path.split("/").filter(Boolean);
+ let current = root;
+ parts.forEach((part, index) => {
+ const leaf = index === parts.length - 1 && !entry.isDirectory;
+ const key = leaf ? part : `${part}/`;
+ let child = current.children.get(key);
+ if (!child) {
+ child = {
+ path: parts.slice(0, index + 1).join("/"),
+ name: part,
+ entry: leaf ? entry : null,
+ children: new Map(),
+ };
+ current.children.set(key, child);
+ }
+ current = child;
+ });
+ }
+ return freeze(root).children;
+}
+
+function flatten(
+ output: ZipTreeRow[],
+ node: ZipTreeNode,
+ depth: number,
+ collapsed: ReadonlySet<string>,
+ query: string,
+): boolean {
+ if (node.entry) {
+ if (query && !node.entry.path.toLowerCase().includes(query)) return false;
+ output.push({ node, depth });
+ return true;
+ }
+ const children: ZipTreeRow[] = [];
+ let visible = !query;
+ if (query || !collapsed.has(node.path)) {
+ for (const child of node.children) {
+ if (flatten(children, child, depth + 1, collapsed, query)) visible = true;
+ }
+ }
+ if (!visible) return false;
+ output.push({ node, depth }, ...children);
+ return true;
+}
+
+export function flattenZipTree(
+ nodes: ReadonlyArray<ZipTreeNode>,
+ collapsed: ReadonlySet<string>,
+ query: string,
+): ReadonlyArray<ZipTreeRow> {
+ const output: ZipTreeRow[] = [];
+ const normalized = query.trim().toLowerCase();
+ for (const node of nodes) flatten(output, node, 0, collapsed, normalized);
+ return output;
+}
+
+export function zipFolderLabel(label: string) {
+ const parts = label.split("/");
+ const name = parts.at(-1) ?? label;
+ if (parts.length > 3) return { prefix: `${parts[0]}/…/${parts.at(-2)}/`, name };
+ return { prefix: parts.length > 1 ? `${parts.slice(0, -1).join("/")}/` : "", name };
+}
+
+export function zipDownloadTimeLeft(input: {
+ readonly receivedBytes: number;
+ readonly totalBytes: number;
+ readonly elapsedMs: number;
+}) {
+ if (input.receivedBytes <= 0 || input.totalBytes <= input.receivedBytes || input.elapsedMs < 1000)
+ return null;
+ const seconds = Math.ceil(
+ ((input.totalBytes - input.receivedBytes) * input.elapsedMs) / input.receivedBytes / 1000,
+ );
+ return seconds < 60
+ ? `About ${seconds} ${seconds === 1 ? "second" : "seconds"} left`
+ : `About ${Math.ceil(seconds / 60)} minutes left`;
+}
diff --git a/apps/mobile/src/lib/attachmentDownload.ts b/apps/mobile/src/lib/attachmentDownload.ts
index 7079003ce45..12ccfd22b72 100644
--- a/apps/mobile/src/lib/attachmentDownload.ts
+++ b/apps/mobile/src/lib/attachmentDownload.ts
@@ -271,6 +271,20 @@ export async function shareLocalAttachment(input: {
}
}
+export async function writeGeneratedAttachmentFile(input: {
+ readonly bytes: Uint8Array;
+ readonly attachment: AttachmentFileMetadata;
+}): Promise<AttachmentPreviewFile> {
+ const cached = await createCachedAttachmentFile(input.attachment);
+ try {
+ await cached.file.write(input.bytes);
+ return cached.preview;
+ } catch (error) {
+ cached.preview.dispose();
+ throw error;
+ }
+}
+
export async function shareGeneratedAttachment(input: {
readonly bytes: Uint8Array;
readonly attachment: AttachmentFileMetadata;
diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts
index 4bf1d1623d0..4a347b2feed 100644
--- a/apps/mobile/src/lib/composerImages.ts
+++ b/apps/mobile/src/lib/composerImages.ts
@@ -220,7 +220,7 @@ export async function removePersistedComposerAttachmentFile(uri: string): Promis
}
}
-async function createComposerFileAttachment(input: {
+export async function createComposerFileAttachment(input: {
readonly uri: string;
readonly name: string;
readonly mimeType: string;
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index eb24fa2a058..6a92a025778 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -14,6 +14,7 @@ const reactTests = [
"src/features/pull-requests/usePullRequestDiff.test.tsx",
"src/components/ProjectFavicon.test.tsx",
"src/components/ui/Dialog.android.test.tsx",
+ "src/features/files/ZipArchiveView.test.tsx",
"src/features/pull-requests/guide/useReviewGuide.test.tsx",
"src/features/settings/SettingsServerControlsRouteScreen.test.tsx",
"src/features/settings/components/BranchNamingSettings.test.tsx",
diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
index d8b2ba6fa3a..fb876688dad 100644
--- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
@@ -47,7 +47,7 @@ import VirtualTablePreview from "./VirtualTablePreview";
import { OfficeFilePreview } from "./OfficeFilePreview";
import { MermaidFilePreview } from "./MermaidFilePreview";
import JSZip from "jszip";
-import { boundedZip } from "./boundedZip";
+import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip";
import BinaryViewer from "./BinaryViewer";
import { decodeImagePreview } from "./decodeImagePreview";
import type { BinaryWorkerResult } from "./binaryPreviewProtocol";
diff --git a/apps/web/src/components/files/binaryPreview.worker.ts b/apps/web/src/components/files/binaryPreview.worker.ts
index 1b170d3cb52..c0f3c2a1741 100644
--- a/apps/web/src/components/files/binaryPreview.worker.ts
+++ b/apps/web/src/components/files/binaryPreview.worker.ts
@@ -1,6 +1,6 @@
import type { Database } from "sql.js";
-import { boundedZip } from "./boundedZip";
+import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip";
import {
ARCHIVE_ENTRY_MAX_BYTES,
ARCHIVE_MAX_ENTRIES,
diff --git a/apps/web/src/components/files/binaryPreviewProtocol.ts b/apps/web/src/components/files/binaryPreviewProtocol.ts
index 137c021ae96..ce94ce4ea09 100644
--- a/apps/web/src/components/files/binaryPreviewProtocol.ts
+++ b/apps/web/src/components/files/binaryPreviewProtocol.ts
@@ -1,7 +1,11 @@
-export const BINARY_PREVIEW_MAX_BYTES = 50 * 1024 * 1024;
-export const ARCHIVE_ENTRY_MAX_BYTES = 10 * 1024 * 1024;
-export const ARCHIVE_MAX_ENTRIES = 2048;
-export const ARCHIVE_MAX_RATIO = 200;
+import { ARCHIVE_MAX_BYTES } from "@t3tools/client-runtime/zip/bounded-zip";
+
+export {
+ ARCHIVE_ENTRY_MAX_BYTES,
+ ARCHIVE_MAX_ENTRIES,
+ ARCHIVE_MAX_RATIO,
+} from "@t3tools/client-runtime/zip/bounded-zip";
+export const BINARY_PREVIEW_MAX_BYTES = ARCHIVE_MAX_BYTES;
export const SQLITE_PAGE_SIZE = 50;
export interface ArchiveEntry {
diff --git a/apps/web/src/components/files/officeArchive.ts b/apps/web/src/components/files/officeArchive.ts
index fe098f6979d..1d952662132 100644
--- a/apps/web/src/components/files/officeArchive.ts
+++ b/apps/web/src/components/files/officeArchive.ts
@@ -1,5 +1,5 @@
import JSZip from "jszip";
-import { checkZipDirectory } from "./zipDirectory";
+import { checkZipDirectory } from "@t3tools/client-runtime/zip/directory";
import { SaxesParser } from "saxes";
import { externalUrl } from "./office/links";
diff --git a/docs/user/composer.md b/docs/user/composer.md
index c3e1ab74ecf..195e81ef771 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -323,7 +323,9 @@ file: a header row with the view toggle, **Copy contents** and **Save file**. On
open in the same file screen as workspace files; its menu holds **Copy contents**, **Save or
share** and **Open in file viewer**. Pictures, videos and PDFs keep their native viewers, and
other document formats such as Word or Pages open in the device's own viewer when it has one.
-If nothing on the device can show a format, save or share it to open it elsewhere.
+If nothing on the device can show a format, save or share it to open it elsewhere. A ZIP up to
+50 MB opens as a folder list on every surface; on mobile, select a file inside it to preview,
+save, or add it to chat.
## Images and videos in messages
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index c08c6e59a2e..66e79c7492a 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -3,6 +3,14 @@
"private": true,
"type": "module",
"exports": {
+ "./zip/bounded-zip": {
+ "types": "./src/zip/boundedZip.ts",
+ "default": "./src/zip/boundedZip.ts"
+ },
+ "./zip/directory": {
+ "types": "./src/zip/zipDirectory.ts",
+ "default": "./src/zip/zipDirectory.ts"
+ },
"./workspace-basename-lookup": {
"types": "./src/workspaceBasenameLookup.ts",
"default": "./src/workspaceBasenameLookup.ts"
@@ -515,6 +523,7 @@
"@t3tools/source-control-core": "workspace:*",
"@t3tools/source-control-definitions": "workspace:*",
"effect": "catalog:",
+ "jszip": "3.10.1",
"three": "0.180.0"
},
"devDependencies": {
diff --git a/apps/web/src/components/files/boundedZip.ts b/packages/client-runtime/src/zip/boundedZip.ts
similarity index 86%
rename from apps/web/src/components/files/boundedZip.ts
rename to packages/client-runtime/src/zip/boundedZip.ts
index 7d9e3319109..d0190f2fa2f 100644
--- a/apps/web/src/components/files/boundedZip.ts
+++ b/packages/client-runtime/src/zip/boundedZip.ts
@@ -1,15 +1,14 @@
import JSZip from "jszip";
-import { checkZipDirectory } from "./zipDirectory";
+import { checkZipDirectory } from "./zipDirectory.ts";
-import {
- ARCHIVE_MAX_ENTRIES,
- ARCHIVE_MAX_RATIO,
- BINARY_PREVIEW_MAX_BYTES,
-} from "./binaryPreviewProtocol";
+export const ARCHIVE_MAX_BYTES = 50 * 1024 * 1024;
+export const ARCHIVE_ENTRY_MAX_BYTES = 10 * 1024 * 1024;
+export const ARCHIVE_MAX_ENTRIES = 2048;
+export const ARCHIVE_MAX_RATIO = 200;
export async function boundedZip(
bytes: ArrayBuffer,
- entryLimit = BINARY_PREVIEW_MAX_BYTES,
+ entryLimit = ARCHIVE_MAX_BYTES,
limits: {
totalLimit?: number;
xmlLimit?: number;
@@ -17,7 +16,7 @@ export async function boundedZip(
markupLimit?: number;
} = {},
) {
- if (bytes.byteLength > BINARY_PREVIEW_MAX_BYTES)
+ if (bytes.byteLength > ARCHIVE_MAX_BYTES)
throw new Error("Preview limited to files under 50 MB.");
checkZipDirectory(bytes, ARCHIVE_MAX_ENTRIES);
const zip = await JSZip.loadAsync(bytes);
@@ -49,7 +48,7 @@ export async function boundedZip(
for (const byte of chunk) if (byte === 0x3c) markup++;
if (
markup > (limits.markupLimit ?? Infinity) ||
- total > (limits.totalLimit ?? BINARY_PREVIEW_MAX_BYTES) ||
+ total > (limits.totalLimit ?? ARCHIVE_MAX_BYTES) ||
total >
Math.max(limits.ratioFloor ?? 0, Math.max(1, bytes.byteLength) * ARCHIVE_MAX_RATIO) ||
length > entryLimit ||
diff --git a/apps/web/src/components/files/zipDirectory.ts b/packages/client-runtime/src/zip/zipDirectory.ts
similarity index 100%
rename from apps/web/src/components/files/zipDirectory.ts
rename to packages/client-runtime/src/zip/zipDirectory.ts
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8ceba3cbcfd..13f9ba0a7be 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1473,6 +1473,9 @@ importers:
effect:
specifier: 4.0.5
version: 4.0.5
+ jszip:
+ specifier: 3.10.1
+ version: 3.10.1
three:
specifier: 0.180.0
version: 0.180.0