@devries-cameron20 / t3code-1 / commits / 5b70d81b0d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

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

Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Bilal Bakr committed Oct 28, 2026 at 00:54 UTC 5b70d81b0d77bdd5883a835173735d55992009af
17 files changed +1525 -114
apps/mobile/src/features/files/AttachmentDocumentBody.tsx new
+111
@@ -0,0 +1,111 @@
1 +import type { EnvironmentId } from "@t3tools/contracts";
2 +import { View } from "react-native";
3 +
4 +import { EmptyState } from "../../components/ui/EmptyState";
5 +import type { useAttachmentDocument } from "../../lib/attachmentDocument";
6 +import { HtmlRenderWebView } from "../threads/HtmlRenderWebView";
7 +import { AudioFilePreview } from "./AudioFilePreview";
8 +import { DelimitedFilePreview } from "./DelimitedFilePreview";
9 +import { FileMarkdownPreview } from "./FileMarkdownPreview";
10 +import { FilePreviewLoading, FilePreviewNotice } from "./FilePreviewFeedback";
11 +import { SourceFileSurface } from "./SourceFileSurface";
12 +import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
13 +
14 +export function nativeViewerKind(kind: ReturnType<typeof useAttachmentDocument>["kind"]) {
15 + if (kind === "image") return "image" as const;
16 + if (kind === "pdf") return "pdf" as const;
17 + if (kind === "video" || kind === "unsupported") return "document" as const;
18 + return null;
19 +}
20 +
21 +export function AttachmentDocumentBody(props: {
22 + readonly document: Pick<
23 + ReturnType<typeof useAttachmentDocument>,
24 + | "kind"
25 + | "activeMode"
26 + | "uri"
27 + | "content"
28 + | "table"
29 + | "error"
30 + | "needsText"
31 + | "retry"
32 + | "revision"
33 + >;
34 + readonly name: string;
35 + readonly environmentId: EnvironmentId | null;
36 + readonly htmlRender: boolean;
37 + readonly nativeViewer: "pending" | "open" | "unavailable" | null;
38 + readonly nativeError: string | null;
39 + readonly onOpenNative: () => void;
40 +}) {
41 + const { document } = props;
42 + if (document.error) {
43 + return (
44 + <View className="flex-1 items-center justify-center bg-sheet px-6">
45 + <EmptyState
46 + title="File unavailable"
47 + detail={document.error}
48 + actionLabel="Try again"
49 + onAction={document.retry}
50 + />
51 + </View>
52 + );
53 + }
54 + if (props.nativeViewer !== null && props.nativeViewer !== "unavailable") {
55 + return <FilePreviewLoading message="Opening in file viewer..." />;
56 + }
57 + // ZIP text entries are read into memory and have no file URI.
58 + if (document.needsText ? !document.content : !document.uri) {
59 + return <FilePreviewLoading message="Loading file..." />;
60 + }
61 + if (document.needsText && document.content) {
62 + const { content, table } = document;
63 + return (
64 + <View className="flex-1 bg-sheet">
65 + {content.truncated ? (
66 + <FilePreviewNotice title="Partial file">
67 + Preview limited to the first 1 MB. Save or share the file to read it in full.
68 + </FilePreviewNotice>
69 + ) : null}
70 + {table && document.activeMode === "table" ? (
71 + <DelimitedFilePreview table={table} />
72 + ) : document.activeMode === "markdown" && props.environmentId ? (
73 + <FileMarkdownPreview
74 + cwd=""
75 + relativePath=""
76 + environmentId={props.environmentId}
77 + threadId={null}
78 + markdown={content.text}
79 + captured
80 + />
81 + ) : (
82 + <SourceFileSurface contents={content.text} path={props.name} selectable />
83 + )}
84 + </View>
85 + );
86 + }
87 + if (!document.uri) return null;
88 + if (document.kind === "audio") {
89 + return <AudioFilePreview key={document.revision} uri={document.uri} onRetry={document.retry} />;
90 + }
91 + if (document.kind === "html") {
92 + return props.htmlRender ? (
93 + <HtmlRenderWebView key={document.uri} uri={document.uri} title={props.name} nested={false} />
94 + ) : (
95 + <WorkspaceFileWebPreview uri={document.uri} />
96 + );
97 + }
98 + return (
99 + <View className="flex-1 items-center justify-center bg-sheet px-6">
100 + <EmptyState
101 + title="No preview for this file"
102 + detail={
103 + props.nativeError ??
104 + "No app on this device can show this format. Save or share it to open it elsewhere."
105 + }
106 + actionLabel="Try again"
107 + onAction={props.onOpenNative}
108 + />
109 + </View>
110 + );
111 +}
apps/mobile/src/features/files/AttachmentFileScreen.tsx
+40 -96
@@ -3,8 +3,11 @@ import * as Dialog from "../../components/ui/Dialog";
3 import { NativeStackScreenOptions } from "../../native/StackHeader";
4 import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
5 import type { MenuAction } from "@react-native-menu/menu";
6 -import { EnvironmentId } from "@t3tools/contracts";
7 -import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
6 +import { EnvironmentId, ThreadId } from "@t3tools/contracts";
7 +import {
8 + clampFileAttachmentUploadBytes,
9 + formatAttachmentSize,
10 +} from "@t3tools/client-runtime/state/attachments";
11 import { useRef, useState } from "react";
12 import { Platform, View } from "react-native";
13
@@ -12,10 +15,7 @@ import {
15 AndroidHeaderIconButton,
16 AndroidScreenHeader,
17 } from "../../components/ui/AndroidScreenHeader";
15 -import { DelimitedFilePreview } from "./DelimitedFilePreview";
16 -import { AudioFilePreview } from "./AudioFilePreview";
18 import { Menu } from "../../components/ui/Menu";
18 -import { EmptyState } from "../../components/ui/EmptyState";
19 import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
20 import { useAttachmentDocument } from "../../lib/attachmentDocument";
21 import { nativeViewerErrorMessage } from "../../lib/attachmentDownload";
@@ -23,12 +23,12 @@ import { isFileBackedComposerAttachment } from "../../lib/composerImages";
23 import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
24 import { useUniwindTheme } from "../../lib/useUniwindTheme";
25 import { removeComposerDraftAttachment, useComposerDraft } from "../../state/use-composer-drafts";
26 -import { FilePreviewLoading, FilePreviewNotice } from "./FilePreviewFeedback";
27 -import { FileMarkdownPreview } from "./FileMarkdownPreview";
26 +import { useEnvironmentServerConfig } from "../../state/entities";
27 +import { useRefreshAssetUrl } from "../../state/assets";
28 +import { scopedThreadKey } from "../../lib/scopedEntities";
29 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
29 -import { SourceFileSurface } from "./SourceFileSurface";
30 -import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
31 -import { HtmlRenderWebView } from "../threads/HtmlRenderWebView";
30 +import { isZipFile, ZipArchiveView } from "./ZipArchiveView";
31 +import { AttachmentDocumentBody, nativeViewerKind } from "./AttachmentDocumentBody";
32
33 export type AttachmentFileRouteParams = {
34 readonly environmentId?: string;
@@ -43,92 +43,6 @@ export type AttachmentFileRouteParams = {
43
44 type AttachmentFileScreenProps = StaticScreenProps<AttachmentFileRouteParams>;
45
46 -function nativeViewerKind(kind: ReturnType<typeof useAttachmentDocument>["kind"]) {
47 - if (kind === "image") return "image" as const;
48 - if (kind === "pdf") return "pdf" as const;
49 - if (kind === "video" || kind === "unsupported") return "document" as const;
50 - return null;
51 -}
52 -
53 -function AttachmentDocumentBody(props: {
54 - readonly document: ReturnType<typeof useAttachmentDocument>;
55 - readonly name: string;
56 - readonly environmentId: EnvironmentId | null;
57 - readonly htmlRender: boolean;
58 - readonly nativeViewer: "pending" | "open" | "unavailable" | null;
59 - readonly nativeError: string | null;
60 - readonly onOpenNative: () => void;
61 -}) {
62 - const { document } = props;
63 - if (document.error) {
64 - return (
65 - <View className="flex-1 items-center justify-center bg-sheet px-6">
66 - <EmptyState
67 - title="File unavailable"
68 - detail={document.error}
69 - actionLabel="Try again"
70 - onAction={document.retry}
71 - />
72 - </View>
73 - );
74 - }
75 - if (props.nativeViewer !== null && props.nativeViewer !== "unavailable") {
76 - return <FilePreviewLoading message="Opening in file viewer..." />;
77 - }
78 - if (!document.uri || (document.needsText && !document.content)) {
79 - return <FilePreviewLoading message="Loading file..." />;
80 - }
81 - if (document.needsText && document.content) {
82 - const { content, table } = document;
83 - return (
84 - <View className="flex-1 bg-sheet">
85 - {content.truncated ? (
86 - <FilePreviewNotice title="Partial file">
87 - Preview limited to the first 1 MB. Save or share the file to read it in full.
88 - </FilePreviewNotice>
89 - ) : null}
90 - {table && document.activeMode === "table" ? (
91 - <DelimitedFilePreview table={table} />
92 - ) : document.activeMode === "markdown" && props.environmentId ? (
93 - <FileMarkdownPreview
94 - cwd=""
95 - relativePath=""
96 - environmentId={props.environmentId}
97 - threadId={null}
98 - markdown={content.text}
99 - captured
100 - />
101 - ) : (
102 - <SourceFileSurface contents={content.text} path={props.name} selectable />
103 - )}
104 - </View>
105 - );
106 - }
107 - if (document.kind === "audio") {
108 - return <AudioFilePreview key={document.revision} uri={document.uri} onRetry={document.retry} />;
109 - }
110 - if (document.kind === "html") {
111 - return props.htmlRender ? (
112 - <HtmlRenderWebView key={document.uri} uri={document.uri} title={props.name} nested={false} />
113 - ) : (
114 - <WorkspaceFileWebPreview uri={document.uri} />
115 - );
116 - }
117 - return (
118 - <View className="flex-1 items-center justify-center bg-sheet px-6">
119 - <EmptyState
120 - title="No preview for this file"
121 - detail={
122 - props.nativeError ??
123 - "No app on this device can show this format. Save or share it to open it elsewhere."
124 - }
125 - actionLabel="Try again"
126 - onAction={props.onOpenNative}
127 - />
128 - </View>
129 - );
130 -}
131 -
46 export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
47 const navigation = useNavigation();
48 const { appearance, setCodeWordBreak } = useAppearancePreferences();
@@ -284,6 +198,36 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
198 menuActions.find(({ id }) => id === event.nativeEvent.event)?.onPress();
199 };
200 const subtitle = `${draftKey ? "Draft attachment" : "Attachment"}${sizeBytes > 0 ? ` · ${formatAttachmentSize(sizeBytes)}` : ""}`;
201 + const refresh = useRefreshAssetUrl(environmentId, resource);
202 + const capabilities = useEnvironmentServerConfig(environmentId)?.environment.capabilities;
203 +
204 + if (document.kind === "archive" && isZipFile(params) && !document.error) {
205 + const threadDraftKey =
206 + environmentId && params.threadId
207 + ? scopedThreadKey(environmentId, ThreadId.make(params.threadId))
208 + : null;
209 + return (
210 + <ZipArchiveView
211 + name={params.name}
212 + subtitle={subtitle}
213 + tintColor={iconColor}
214 + sizeBytes={sizeBytes}
215 + uri={uri}
216 + isLocal={localAttachment !== null}
217 + refresh={refresh}
218 + environmentId={environmentId}
219 + // Entries go to the thread's chat composer, also from a question-answer draft.
220 + draftKey={threadDraftKey ?? draftKey}
221 + maxAttachmentBytes={
222 + capabilities?.attachmentUploads && capabilities.fileAttachments
223 + ? clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes)
224 + : undefined
225 + }
226 + onSave={() => void share()}
227 + onRemove={draftKey ? removeFromDraft : null}
228 + />
229 + );
230 + }
231
232 return (
233 <View className="flex-1 bg-sheet">
apps/mobile/src/features/files/ZipArchiveView.test.tsx new
+315
@@ -0,0 +1,315 @@
1 +import { AsyncResult } from "effect/reactivity";
2 +import { act, type ComponentProps, type ReactNode } from "react";
3 +import { createRoot } from "react-dom/client";
4 +import { expect, it, onTestFinished, vi } from "vite-plus/test";
5 +import type { ServerConfig } from "@t3tools/contracts";
6 +
7 +import type { ZipTreeRow } from "./zipTree";
8 +
9 +const files = vi.hoisted(() => new Map<string, Uint8Array>());
10 +const navigation = vi.hoisted(() => ({ remove: null as (() => void) | null }));
11 +const server = vi.hoisted(() => ({
12 + capabilities: { repositoryIdentity: false } as ServerConfig["environment"]["capabilities"],
13 + refresh: vi.fn(async () => "file:///first.zip"),
14 +}));
15 +
16 +vi.mock("../../state/entities", () => ({
17 + useEnvironmentServerConfig: () => ({ environment: { capabilities: server.capabilities } }),
18 +}));
19 +vi.mock("../../state/assets", () => ({
20 + useRefreshAssetUrl: () => server.refresh,
21 + useFreshAssetUrl: () => AsyncResult.success({ url: "file:///first.zip", authorizedAt: 0 }),
22 +}));
23 +
24 +vi.mock("react-native", () => {
25 + const Slot = (props: { readonly children?: ReactNode }) => <div>{props.children}</div>;
26 + return {
27 + View: Slot,
28 + Text: Slot,
29 + ScrollView: Slot,
30 + ActivityIndicator: () => null,
31 + Platform: { OS: "ios" },
32 + Keyboard: { dismiss: vi.fn() },
33 + Pressable: (props: {
34 + readonly children?: ReactNode;
35 + readonly accessibilityLabel?: string;
36 + readonly disabled?: boolean;
37 + readonly onPress?: () => void;
38 + }) => (
39 + <button
40 + aria-label={props.accessibilityLabel}
41 + disabled={props.disabled}
42 + onClick={props.onPress}
43 + >
44 + {props.children}
45 + </button>
46 + ),
47 + TextInput: (props: {
48 + readonly accessibilityLabel?: string;
49 + readonly value: string;
50 + readonly onChangeText: (value: string) => void;
51 + }) => (
52 + <input
53 + aria-label={props.accessibilityLabel}
54 + value={props.value}
55 + onChange={(event) => props.onChangeText(event.target.value)}
56 + />
57 + ),
58 + };
59 +});
60 +vi.mock("@legendapp/list/react-native", () => ({
61 + LegendList: (props: {
62 + readonly data: ZipTreeRow[];
63 + readonly ListHeaderComponent: ReactNode;
64 + readonly ListEmptyComponent: ReactNode;
65 + readonly keyExtractor: (row: ZipTreeRow) => string;
66 + readonly renderItem: (input: { item: ZipTreeRow }) => ReactNode;
67 + }) => (
68 + <div>
69 + {props.ListHeaderComponent}
70 + {props.data.length === 0 ? props.ListEmptyComponent : null}
71 + {props.data.map((item) => (
72 + <div key={props.keyExtractor(item)}>{props.renderItem({ item })}</div>
73 + ))}
74 + </div>
75 + ),
76 +}));
77 +vi.mock("expo-file-system", () => ({
78 + Directory: class {
79 + create() {}
80 + },
81 + Paths: { document: { uri: "file:///documents" } },
82 + File: class {
83 + constructor(private readonly uri: string) {}
84 + get exists() {
85 + return false;
86 + }
87 + get size() {
88 + return files.get(this.uri)?.byteLength ?? null;
89 + }
90 + async arrayBuffer() {
91 + const bytes = files.get(this.uri);
92 + if (!bytes) throw new Error(`Missing ZIP fixture: ${this.uri}`);
93 + return Uint8Array.from(bytes).buffer;
94 + }
95 + },
96 +}));
97 +vi.mock("expo/fetch", () => ({ fetch: vi.fn() }));
98 +vi.mock("expo-crypto", () => ({ randomUUID: vi.fn() }));
99 +vi.mock("@react-navigation/native", () => ({
100 + useNavigation: () => ({ canGoBack: () => false }),
101 + usePreventRemove: (enabled: boolean, remove: () => void) => {
102 + navigation.remove = enabled ? remove : null;
103 + },
104 +}));
105 +vi.mock("react-native-safe-area-context", () => ({
106 + useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
107 +}));
108 +vi.mock("../../native/NativeScrollViewMarker", () => ({ NativeScrollView: () => null }));
109 +vi.mock("../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null }));
110 +vi.mock("../../components/ui/Toolbar", () => {
111 + const Slot = (props: { readonly children?: ReactNode }) => <div>{props.children}</div>;
112 + return {
113 + Toolbar: Object.assign(Slot, {
114 + Button: () => null,
115 + Menu: Slot,
116 + MenuAction: (props: {
117 + readonly children?: ReactNode;
118 + readonly disabled?: boolean;
119 + readonly onPress?: () => void;
120 + }) => (
121 + <button disabled={props.disabled} onClick={props.onPress}>
122 + {props.children}
123 + </button>
124 + ),
125 + }),
126 + };
127 +});
128 +vi.mock("../../components/ui/AndroidScreenHeader", () => ({ AndroidScreenHeader: () => null }));
129 +vi.mock("../../components/ui/Menu", () => ({ Menu: () => null }));
130 +vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
131 +vi.mock("../../components/ui/Progress", () => ({ Progress: () => null }));
132 +vi.mock("../../components/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
133 +vi.mock("../../components/FilePreviewModal", () => ({ FilePreviewModal: () => null }));
134 +vi.mock("../../lib/copyTextWithHaptic", () => ({}));
135 +vi.mock("./SourceFileSurface", () => ({
136 + SourceFileSurface: (props: { readonly contents: string }) => <pre>{props.contents}</pre>,
137 +}));
138 +vi.mock("./AudioFilePreview", () => ({ AudioFilePreview: () => null }));
139 +vi.mock("./FileMarkdownPreview", () => ({ FileMarkdownPreview: () => null }));
140 +vi.mock("./WorkspaceFileWebPreview", () => ({ WorkspaceFileWebPreview: () => null }));
141 +vi.mock("../threads/HtmlRenderWebView", () => ({ HtmlRenderWebView: () => null }));
142 +vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
143 + useAppearancePreferences: () => ({
144 + appearance: { codeWordBreak: false },
145 + themeVariables: { "--color-icon": "#000000" },
146 + setCodeWordBreak: () => {},
147 + }),
148 +}));
149 +
150 +import { ZipArchiveView } from "./ZipArchiveView";
151 +import { AttachmentFileScreen } from "./AttachmentFileScreen";
152 +import { appAtomRegistry } from "../../state/atom-registry";
153 +import { composerDraftsAtom } from "../../state/use-composer-drafts";
154 +
155 +function setup() {
156 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
157 + vi.useFakeTimers({ toFake: ["setImmediate", "clearImmediate"] });
158 + files.clear();
159 + navigation.remove = null;
160 + server.capabilities = { repositoryIdentity: false };
161 + server.refresh.mockClear();
162 + appAtomRegistry.set(composerDraftsAtom, {});
163 + files.set(
164 + "file:///first.zip",
165 + Uint8Array.from(
166 + atob(
167 + "UEsDBBQAAAAAAAAAIVyzyFShFgAAABYAAAAJAAAAZmlyc3QudHh0Rmlyc3QgYXJjaGl2ZSBjb250ZW50c1BLAQIUAxQAAAAAAAAAIVyzyFShFgAAABYAAAAJAAAAAAAAAAAAAACAAQAAAABmaXJzdC50eHRQSwUGAAAAAAEAAQA3AAAAPQAAAAAA",
168 + ),
169 + (character) => character.charCodeAt(0),
170 + ),
171 + );
172 +
173 + const container = document.createElement("div");
174 + const root = createRoot(container);
175 + onTestFinished(() => {
176 + act(() => root.unmount());
177 + files.clear();
178 + vi.useRealTimers();
179 + vi.unstubAllGlobals();
180 + });
181 + const props: ComponentProps<typeof ZipArchiveView> = {
182 + name: "archive.zip",
183 + subtitle: "ZIP",
184 + tintColor: "#000000",
185 + sizeBytes: 0,
186 + uri: "file:///first.zip",
187 + isLocal: true,
188 + refresh: async () => null,
189 + environmentId: null,
190 + draftKey: null,
191 + maxAttachmentBytes: undefined,
192 + onSave: () => {},
193 + onRemove: null,
194 + };
195 + return {
196 + container,
197 + root,
198 + props,
199 + render: async (input = props) => {
200 + await act(async () => root.render(<ZipArchiveView {...input} />));
201 + },
202 + settle: async (assert: () => void) => {
203 + await act(async () => vi.runAllTimersAsync());
204 + assert();
205 + },
206 + };
207 +}
208 +
209 +it("opens a ZIP chat attachment as a browsable archive on the attachment file screen", async () => {
210 + const screen = setup();
211 + server.capabilities = {
212 + repositoryIdentity: false,
213 + attachmentUploads: true,
214 + fileAttachments: { maxUploadBytes: 1024 },
215 + };
216 + const { fetch } = await import("expo/fetch");
217 + vi.mocked(fetch, { partial: true }).mockImplementation(async () => ({
218 + ok: true,
219 + body: new Response(Uint8Array.from(files.get("file:///first.zip")!)).body,
220 + }));
221 + await act(async () =>
222 + screen.root.render(
223 + <AttachmentFileScreen
224 + route={{
225 + params: {
226 + environmentId: "environment-1",
227 + threadId: "thread-1",
228 + attachmentId: "attachment-1",
229 + name: "archive.zip",
230 + mimeType: "application/zip",
231 + sizeBytes: "200",
232 + },
233 + }}
234 + />,
235 + ),
236 + );
237 + await screen.settle(() =>
238 + expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull(),
239 + );
240 + await act(async () =>
241 + screen.container.querySelector<HTMLButtonElement>('[aria-label="first.txt"]')!.click(),
242 + );
243 + await screen.settle(() =>
244 + expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
245 + );
246 + const add = Array.from(screen.container.querySelectorAll("button")).find(
247 + (button) => button.textContent === "Add to chat",
248 + );
249 + expect(add?.disabled).toBe(false);
250 +});
251 +
252 +it("keeps the ZIP filter and archive open when native Back closes a selected entry", async () => {
253 + const screen = setup();
254 + await screen.render();
255 + await screen.settle(() =>
256 + expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull(),
257 + );
258 + const filter = screen.container.querySelector<HTMLInputElement>(
259 + '[aria-label="Filter files in ZIP"]',
260 + )!;
261 + await act(async () => {
262 + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(
263 + filter,
264 + "first",
265 + );
266 + filter.dispatchEvent(new Event("input", { bubbles: true }));
267 + });
268 + await act(async () =>
269 + screen.container.querySelector<HTMLButtonElement>('[aria-label="first.txt"]')!.click(),
270 + );
271 + await screen.settle(() =>
272 + expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
273 + );
274 +
275 + expect(navigation.remove).not.toBeNull();
276 + await act(async () => navigation.remove!());
277 +
278 + expect(screen.container.querySelector("pre")).toBeNull();
279 + expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull();
280 + expect(
281 + screen.container.querySelector<HTMLInputElement>('[aria-label="Filter files in ZIP"]')?.value,
282 + ).toBe("first");
283 +});
284 +
285 +it("explains why an encrypted ZIP cannot be browsed", async () => {
286 + const screen = setup();
287 + const bytes = files.get("file:///first.zip")!;
288 + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
289 + const directory = view.getUint32(bytes.length - 6, true);
290 + view.setUint16(directory + 8, view.getUint16(directory + 8, true) | 1, true);
291 + await screen.render();
292 + await screen.settle(() => expect(screen.container.textContent).toContain("Encrypted zip"));
293 + expect(screen.container.querySelector('[aria-label="first.txt"]')).toBeNull();
294 +});
295 +
296 +it("keeps the archive and selected entry when the parent re-renders with a new refresh", async () => {
297 + const screen = setup();
298 + await screen.render();
299 + await screen.settle(() =>
300 + expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull(),
301 + );
302 + await act(async () =>
303 + screen.container.querySelector<HTMLButtonElement>('[aria-label="first.txt"]')!.click(),
304 + );
305 + await screen.settle(() =>
306 + expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
307 + );
308 + files.delete("file:///first.zip");
309 +
310 + await screen.render({ ...screen.props, refresh: async () => null });
311 + await screen.settle(() =>
312 + expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
313 + );
314 + expect(navigation.remove).not.toBeNull();
315 +});
apps/mobile/src/features/files/ZipArchiveView.tsx new
+870
@@ -0,0 +1,870 @@
1 +import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
2 +import {
3 + ARCHIVE_ENTRY_MAX_BYTES,
4 + ARCHIVE_MAX_BYTES,
5 + boundedZip,
6 +} from "@t3tools/client-runtime/zip/bounded-zip";
7 +import type { EnvironmentId } from "@t3tools/contracts";
8 +import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
9 +import {
10 + decodeFilePreviewText,
11 + filePreviewKind,
12 + hostPreviewMimeTypeFromExtension,
13 +} from "@t3tools/shared/filePreview";
14 +import { LegendList } from "@legendapp/list/react-native";
15 +import { fetch } from "expo/fetch";
16 +import { File } from "expo-file-system";
17 +import { useNavigation, usePreventRemove } from "@react-navigation/native";
18 +import { useEffect, useEffectEvent, useRef, useState } from "react";
19 +import { Keyboard, Platform, Pressable, ScrollView, TextInput, View } from "react-native";
20 +import { useSafeAreaInsets } from "react-native-safe-area-context";
21 +
22 +import { PierreEntryIcon } from "../../components/PierreEntryIcon";
23 +import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader";
24 +import { SymbolView } from "../../components/ui/AppSymbol";
25 +import { AppText as Text } from "../../components/ui/AppText";
26 +import { Button } from "../../components/ui/Button";
27 +import { EmptyState } from "../../components/ui/EmptyState";
28 +import { Progress } from "../../components/ui/Progress";
29 +import { Toolbar } from "../../components/ui/Toolbar";
30 +import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
31 +import { NativeScrollView } from "../../native/NativeScrollViewMarker";
32 +import { NativeStackScreenOptions } from "../../native/StackHeader";
33 +import * as Dialog from "../../components/ui/Dialog";
34 +import { FilePreviewModal } from "../../components/FilePreviewModal";
35 +import {
36 + nativeViewerErrorMessage,
37 + shareGeneratedAttachment,
38 + writeGeneratedAttachmentFile,
39 +} from "../../lib/attachmentDownload";
40 +import { attachmentDocumentPresentation } from "../../lib/attachmentDocumentPresentation";
41 +import {
42 + createComposerFileAttachment,
43 + removePersistedComposerAttachmentFile,
44 +} from "../../lib/composerImages";
45 +import { appendComposerDraftAttachments } from "../../state/use-composer-drafts";
46 +import { AttachmentDocumentBody, nativeViewerKind } from "./AttachmentDocumentBody";
47 +import { FilePreviewLoading } from "./FilePreviewFeedback";
48 +import {
49 + buildZipTree,
50 + flattenZipTree,
51 + zipDownloadTimeLeft,
52 + zipFolderLabel,
53 + type ZipEntry,
54 + type ZipTreeRow,
55 +} from "./zipTree";
56 +
57 +export function isZipFile(file: { readonly name: string; readonly mimeType: string }) {
58 + const mime = file.mimeType.split(";", 1)[0]?.trim().toLowerCase();
59 + return (
60 + mime === "application/zip" ||
61 + mime === "application/x-zip-compressed" ||
62 + file.name.toLowerCase().endsWith(".zip")
63 + );
64 +}
65 +
66 +interface ZipArchive {
67 + readonly entries: ReadonlyArray<ZipEntry>;
68 + readonly fileCount: number;
69 +}
70 +
71 +interface ZipFailure {
72 + readonly title: string;
73 + readonly detail: string;
74 + readonly retry: boolean;
75 +}
76 +
77 +const SAVE_ZIP_HINT = "Save the ZIP to open it in another app.";
78 +const TOO_LARGE: ZipFailure = {
79 + title: "Too large to browse here",
80 + detail: `Browsing works up to ${formatAttachmentSize(ARCHIVE_MAX_BYTES)}. ${SAVE_ZIP_HINT}`,
81 + retry: false,
82 +};
83 +const CANCELLED: ZipFailure = {
84 + title: "Download cancelled",
85 + detail: "The ZIP wasn't downloaded. Try again to list its files.",
86 + retry: true,
87 +};
88 +const NETWORK: ZipFailure = {
89 + title: "Couldn't download this ZIP",
90 + detail: "Check the connection to this environment and try again.",
91 + retry: true,
92 +};
93 +
94 +class ZipFailureError extends Error {
95 + constructor(readonly failure: ZipFailure) {
96 + super(failure.title);
97 + }
98 +}
99 +
100 +function errorMessage(cause: unknown, fallback: string) {
101 + return cause instanceof Error ? cause.message : fallback;
102 +}
103 +
104 +async function readArchiveBody(
105 + body: ReadableStream<Uint8Array>,
106 + onProgress: (receivedBytes: number) => void,
107 +) {
108 + const reader = body.getReader();
109 + const chunks: Uint8Array[] = [];
110 + let size = 0;
111 + try {
112 + while (true) {
113 + const { value, done } = await reader.read();
114 + if (done) break;
115 + size += value.byteLength;
116 + if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
117 + chunks.push(value);
118 + onProgress(size);
119 + }
120 + } finally {
121 + void reader.cancel().catch(() => {});
122 + }
123 + const bytes = new Uint8Array(size);
124 + let offset = 0;
125 + for (const chunk of chunks) {
126 + bytes.set(chunk, offset);
127 + offset += chunk.byteLength;
128 + }
129 + return bytes.buffer;
130 +}
131 +
132 +async function openArchive(bytes: ArrayBuffer): Promise<ZipArchive> {
133 + let files: Awaited<ReturnType<typeof boundedZip>>;
134 + try {
135 + files = await boundedZip(bytes);
136 + } catch (cause) {
137 + throw new ZipFailureError({
138 + title: "Couldn't browse this ZIP",
139 + detail: `${errorMessage(cause, "It may be incomplete or damaged.")} ${SAVE_ZIP_HINT}`,
140 + retry: false,
141 + });
142 + }
143 + const entries = [...files].map(([path, file]): ZipEntry => {
144 + const name = path.split("/").findLast(Boolean) ?? path;
145 + const dot = name.lastIndexOf(".");
146 + return {
147 + path,
148 + name,
149 + isDirectory: file.directory,
150 + sizeBytes: file.bytes.byteLength,
151 + mimeType:
152 + (dot > 0 ? hostPreviewMimeTypeFromExtension(name.slice(dot).toLowerCase()) : null) ??
153 + "application/octet-stream",
154 + bytes: file.bytes,
155 + };
156 + });
157 + return { entries, fileCount: entries.filter((entry) => !entry.isDirectory).length };
158 +}
159 +
160 +type ArchiveState =
161 + | { readonly status: "loading"; readonly receivedBytes: number; readonly timeLeft: string | null }
162 + | { readonly status: "ready"; readonly archive: ZipArchive }
163 + | { readonly status: "failed"; readonly failure: ZipFailure };
164 +
165 +function useZipArchive(input: {
166 + readonly uri: string | null;
167 + readonly isLocal: boolean;
168 + readonly sizeBytes: number;
169 + readonly refresh: () => Promise<string | null>;
170 +}) {
171 + const [state, setState] = useState<ArchiveState>({
172 + status: "loading",
173 + receivedBytes: 0,
174 + timeLeft: null,
175 + });
176 + const [revision, setRevision] = useState(0);
177 + const controller = useRef<AbortController | null>(null);
178 + const { uri, isLocal, sizeBytes } = input;
179 + // The parent mints a new refresh callback on every render; it must not reload the archive.
180 + const refresh = useEffectEvent(input.refresh);
181 + // oxlint-disable-next-line t3code/react-effect-budget -- Load archive bytes and cancel the stream on cleanup.
182 + useEffect(() => {
183 + if (!uri) return;
184 + const abort = new AbortController();
185 + controller.current = abort;
186 + const startedAt = Date.now();
187 + // oxlint-disable-next-line react/set-state-in-effect -- A new archive load resets its progress.
188 + setState({ status: "loading", receivedBytes: 0, timeLeft: null });
189 + void (async () => {
190 + if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
191 + if (isLocal) {
192 + const file = new File(uri);
193 + if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError(TOO_LARGE);
194 + return openArchive(await file.arrayBuffer());
195 + }
196 + const url = (await refresh()) ?? uri;
197 + const response = await fetch(url, { signal: abort.signal });
198 + if (!response.ok || !response.body) throw new ZipFailureError(NETWORK);
199 + const bytes = await readArchiveBody(response.body, (receivedBytes) =>
200 + setState({
201 + status: "loading",
202 + receivedBytes,
203 + timeLeft: zipDownloadTimeLeft({
204 + receivedBytes,
205 + totalBytes: sizeBytes,
206 + elapsedMs: Date.now() - startedAt,
207 + }),
208 + }),
209 + );
210 + abort.signal.throwIfAborted();
211 + return openArchive(bytes);
212 + })()
213 + .then((archive) => {
214 + if (!abort.signal.aborted) setState({ status: "ready", archive });
215 + })
216 + .catch((cause: unknown) => {
217 + if (!abort.signal.aborted)
218 + setState({
219 + status: "failed",
220 + failure: cause instanceof ZipFailureError ? cause.failure : NETWORK,
221 + });
222 + });
223 + return () => abort.abort();
224 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reload the archive.
225 + }, [uri, isLocal, sizeBytes, revision]);
226 + return {
227 + state,
228 + retry: () => setRevision((value) => value + 1),
229 + cancel: () => {
230 + controller.current?.abort();
231 + setState({ status: "failed", failure: CANCELLED });
232 + },
233 + };
234 +}
235 +
236 +function ZipTreeRowView(props: {
237 + readonly row: ZipTreeRow;
238 + readonly collapsed: boolean;
239 + readonly onToggle: (path: string) => void;
240 + readonly onOpen: (entry: ZipEntry) => void;
241 +}) {
242 + const { node, depth } = props.row;
243 + const entry = node.entry;
244 + const folder = entry ? null : zipFolderLabel(node.label);
245 + return (
246 + <Pressable
247 + accessibilityRole="button"
248 + accessibilityLabel={entry ? entry.path : `${node.path} folder`}
249 + accessibilityState={entry ? undefined : { expanded: !props.collapsed }}
250 + onPress={() => (entry ? props.onOpen(entry) : props.onToggle(node.path))}
251 + className="mx-2 h-11 flex-row items-center gap-1.5 rounded-lg pr-2.5 active:bg-subtle"
252 + style={{ paddingLeft: 8 + depth * 18 }}
253 + >
254 + <View className="w-4 items-center">
255 + {entry ? null : (
256 + <SymbolView
257 + name={props.collapsed ? "chevron.right" : "chevron.down"}
258 + size={12}
259 + tintColorClassName="accent-icon-muted"
260 + type="monochrome"
261 + />
262 + )}
263 + </View>
264 + <View className="w-5 items-center">
265 + <PierreEntryIcon path={node.path} kind={entry ? "file" : "directory"} size={17} />
266 + </View>
267 + <Text className="min-w-0 flex-1 text-[15px] text-foreground" numberOfLines={1}>
268 + {folder ? (
269 + <>
270 + <Text className="text-[15px] text-foreground-muted">{folder.prefix}</Text>
271 + {folder.name}
272 + </>
273 + ) : (
274 + node.label
275 + )}
276 + </Text>
277 + <Text className="text-xs text-foreground-muted">
278 + {entry
279 + ? formatAttachmentSize(entry.sizeBytes)
280 + : props.collapsed
281 + ? `${node.fileCount} ${node.fileCount === 1 ? "file" : "files"}`
282 + : ""}
283 + </Text>
284 + </Pressable>
285 + );
286 +}
287 +
288 +function ZipArchiveHeader(props: {
289 + readonly name: string;
290 + readonly subtitle: string;
291 + readonly tintColor: string;
292 + readonly onSave: () => void;
293 + readonly onRemove: (() => void) | null;
294 +}) {
295 + const navigation = useNavigation();
296 + const isAndroid = Platform.OS === "android";
297 + return (
298 + <>
299 + <NativeStackScreenOptions
300 + options={{
301 + headerShown: !isAndroid,
302 + headerTintColor: props.tintColor,
303 + headerTitle: props.name,
304 + title: props.name,
305 + unstable_headerSubtitle: isAndroid ? undefined : props.subtitle,
306 + }}
307 + />
308 + {isAndroid ? (
309 + <AndroidScreenHeader
310 + title={props.name}
311 + subtitle={props.subtitle}
312 + onBack={() => {
313 + if (navigation.canGoBack()) navigation.goBack();
314 + }}
315 + actions={[
316 + { accessibilityLabel: "Save ZIP", icon: "square.and.arrow.up", onPress: props.onSave },
317 + ...(props.onRemove
318 + ? [
319 + {
320 + accessibilityLabel: "Remove from draft",
321 + icon: "trash" as const,
322 + onPress: props.onRemove,
323 + destructive: true,
324 + overflowOnly: true,
325 + },
326 + ]
327 + : []),
328 + ]}
329 + />
330 + ) : (
331 + <Toolbar placement="right">
332 + {props.onRemove ? (
333 + <Toolbar.Menu accessibilityLabel="ZIP actions" icon="ellipsis">
334 + <Toolbar.MenuAction icon="square.and.arrow.up" onPress={props.onSave}>
335 + Save ZIP
336 + </Toolbar.MenuAction>
337 + <Toolbar.MenuAction icon="trash" destructive onPress={props.onRemove}>
338 + Remove from draft
339 + </Toolbar.MenuAction>
340 + </Toolbar.Menu>
341 + ) : (
342 + <Toolbar.Button
343 + accessibilityLabel="Save ZIP"
344 + icon="square.and.arrow.up"
345 + onPress={props.onSave}
346 + />
347 + )}
348 + </Toolbar>
349 + )}
350 + </>
351 + );
352 +}
353 +
354 +function ZipArchiveProgress(props: {
355 + readonly receivedBytes: number;
356 + readonly totalBytes: number;
357 + readonly timeLeft: string | null;
358 + readonly onCancel: () => void;
359 +}) {
360 + const { timeLeft } = props;
361 + return (
362 + <View className="flex-1 justify-center gap-3 bg-sheet px-8">
363 + <Text className="text-xl font-t3-semibold text-foreground">
364 + {formatAttachmentSize(props.receivedBytes)}
365 + {props.totalBytes > 0 ? (
366 + <Text className="text-xl text-foreground-muted">
367 + {` of ${formatAttachmentSize(props.totalBytes)}`}
368 + </Text>
369 + ) : null}
370 + </Text>
371 + <Progress
372 + value={props.totalBytes > 0 ? props.receivedBytes / props.totalBytes : undefined}
373 + label="ZIP download progress"
374 + />
375 + <Text className="text-sm text-foreground-muted">
376 + {`Downloading the ZIP so its files can be listed.${timeLeft ? ` ${timeLeft} on this connection.` : ""}`}
377 + </Text>
378 + <Button label="Cancel" onPress={props.onCancel} />
379 + </View>
380 + );
381 +}
382 +
383 +function ZipArchiveFailure(props: {
384 + readonly failure: ZipFailure;
385 + readonly onRetry: () => void;
386 + readonly onSave: () => void;
387 +}) {
388 + return (
389 + <View className="flex-1 items-center justify-center bg-sheet px-6">
390 + <EmptyState
391 + variant="plain"
392 + title={props.failure.title}
393 + detail={props.failure.detail}
394 + action={
395 + <View className="flex-row gap-3">
396 + {props.failure.retry ? (
397 + <Button tone="primary" label="Try again" onPress={props.onRetry} />
398 + ) : null}
399 + <Button
400 + tone={props.failure.retry ? "secondary" : "primary"}
401 + label="Save ZIP"
402 + onPress={props.onSave}
403 + />
404 + </View>
405 + }
406 + />
407 + </View>
408 + );
409 +}
410 +
411 +function ZipArchiveList(props: {
412 + readonly archive: ZipArchive;
413 + readonly headerInset: number;
414 + readonly onOpen: (entry: ZipEntry) => void;
415 +}) {
416 + const [query, setQuery] = useState("");
417 + const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
418 + const { archive } = props;
419 + const rows = flattenZipTree(buildZipTree(archive.entries), collapsed, query);
420 + const toggle = (path: string) =>
421 + setCollapsed((current) => {
422 + const next = new Set(current);
423 + if (!next.delete(path)) next.add(path);
424 + return next;
425 + });
426 + const fileCount = archive.fileCount;
427 + return (
428 + <View className="flex-1 bg-sheet">
429 + <LegendList
430 + renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
431 + contentInsetStartAdjustment={props.headerInset}
432 + className="flex-1"
433 + data={rows}
434 + keyExtractor={(row) => `${row.node.entry ? "f" : "d"}:${row.node.path}`}
435 + contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
436 + automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
437 + estimatedItemSize={44}
438 + recycleItems
439 + keyboardDismissMode="on-drag"
440 + keyboardShouldPersistTaps="handled"
441 + extraData={collapsed}
442 + contentContainerStyle={{ paddingBottom: 4 }}
443 + ListHeaderComponent={
444 + <View className="px-4 pt-3 pb-2.5">
445 + <View className="h-[38px] flex-row items-center gap-2 rounded-[10px] bg-subtle px-3">
446 + <SymbolView name="magnifyingglass" size={15} tintColorClassName="accent-icon-muted" />
447 + <TextInput
448 + accessibilityLabel="Filter files in ZIP"
449 + autoCapitalize="none"
450 + autoCorrect={false}
451 + placeholder={`Filter ${fileCount} ${fileCount === 1 ? "file" : "files"}`}
452 + placeholderTextColorClassName="accent-placeholder"
453 + cursorColorClassName="accent-focus"
454 + className="min-w-0 flex-1 font-sans text-[15px] text-foreground"
455 + value={query}
456 + onChangeText={setQuery}
457 + />
458 + {query ? (
459 + <Pressable
460 + accessibilityRole="button"
461 + accessibilityLabel="Clear filter"
462 + hitSlop={10}
463 + onPress={() => setQuery("")}
464 + >
465 + <SymbolView
466 + name="xmark.circle.fill"
467 + size={16}
468 + tintColorClassName="accent-icon-muted"
469 + />
470 + </Pressable>
471 + ) : null}
472 + </View>
473 + </View>
474 + }
475 + renderItem={({ item }) => (
476 + <ZipTreeRowView
477 + row={item}
478 + collapsed={collapsed.has(item.node.path)}
479 + onToggle={toggle}
480 + onOpen={props.onOpen}
481 + />
482 + )}
483 + ListEmptyComponent={
484 + query ? (
485 + <EmptyState
486 + variant="plain"
487 + title={`No files match “${query.trim()}”`}
488 + detail="The filter checks file names and folder paths."
489 + action={<Button label="Clear filter" onPress={() => setQuery("")} />}
490 + />
491 + ) : (
492 + <EmptyState variant="plain" title="This ZIP is empty" detail="It has no files." />
493 + )
494 + }
495 + />
496 + </View>
497 + );
498 +}
499 +
500 +export function ZipArchiveView(props: {
501 + readonly name: string;
502 + readonly subtitle: string;
503 + readonly tintColor: string;
504 + readonly sizeBytes: number;
505 + readonly uri: string | null;
506 + readonly isLocal: boolean;
507 + readonly refresh: () => Promise<string | null>;
508 + readonly environmentId: EnvironmentId | null;
509 + readonly draftKey: string | null;
510 + readonly maxAttachmentBytes: number | undefined;
511 + readonly onSave: () => void;
512 + readonly onRemove: (() => void) | null;
513 +}) {
514 + const { state, retry, cancel } = useZipArchive(props);
515 + const [selection, setSelection] = useState<{
516 + readonly archive: ZipArchive;
517 + readonly entry: ZipEntry;
518 + } | null>(null);
519 + const archive = state.status === "ready" ? state.archive : null;
520 + const selected = selection && selection.archive === archive ? selection.entry : null;
521 + const entryOpen = selected !== null;
522 + usePreventRemove(entryOpen, () => setSelection(null));
523 + const insets = useSafeAreaInsets();
524 + const columnMetrics = useNativeColumnLayoutMetrics();
525 + const headerInset = Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
526 + return (
527 + <View className="flex-1 bg-sheet">
528 + {entryOpen ? null : (
529 + <ZipArchiveHeader
530 + name={props.name}
531 + subtitle={
532 + archive
533 + ? `${archive.fileCount} ${archive.fileCount === 1 ? "file" : "files"}${props.sizeBytes > 0 ? ` · ${formatAttachmentSize(props.sizeBytes)}` : ""}`
534 + : props.subtitle
535 + }
536 + tintColor={props.tintColor}
537 + onSave={props.onSave}
538 + onRemove={props.onRemove}
539 + />
540 + )}
541 + {state.status === "ready" ? (
542 + <ZipArchiveList
543 + archive={state.archive}
544 + headerInset={headerInset}
545 + onOpen={(entry) => {
546 + Keyboard.dismiss();
547 + setSelection({ archive: state.archive, entry });
548 + }}
549 + />
550 + ) : (
551 + <View className="flex-1" style={{ paddingTop: headerInset }}>
552 + {state.status === "loading" ? (
553 + props.isLocal || state.receivedBytes === 0 ? (
554 + <FilePreviewLoading message="Opening ZIP..." />
555 + ) : (
556 + <ZipArchiveProgress
557 + receivedBytes={state.receivedBytes}
558 + totalBytes={props.sizeBytes}
559 + timeLeft={state.timeLeft}
560 + onCancel={cancel}
561 + />
562 + )
563 + ) : (
564 + <ZipArchiveFailure failure={state.failure} onRetry={retry} onSave={props.onSave} />
565 + )}
566 + </View>
567 + )}
568 + {selected ? (
569 + <View className="absolute inset-0">
570 + <ZipEntryView
571 + key={selected.path}
572 + archiveName={props.name}
573 + entry={selected}
574 + environmentId={props.environmentId}
575 + draftKey={props.draftKey}
576 + maxAttachmentBytes={props.maxAttachmentBytes}
577 + onBack={() => setSelection(null)}
578 + />
579 + </View>
580 + ) : null}
581 + </View>
582 + );
583 +}
584 +
585 +async function addZipEntryToDraft(input: {
586 + readonly entry: ZipEntry;
587 + readonly draftKey: string;
588 + readonly maxBytes: number;
589 + readonly signal: AbortSignal;
590 +}) {
591 + const { entry, signal } = input;
592 + const file = await writeGeneratedAttachmentFile({
593 + bytes: entry.bytes,
594 + attachment: { name: entry.name, mimeType: entry.mimeType },
595 + });
596 + try {
597 + signal.throwIfAborted();
598 + const attachment = await createComposerFileAttachment({
599 + uri: file.uri,
600 + name: entry.name,
601 + mimeType: entry.mimeType,
602 + sizeBytes: entry.sizeBytes,
603 + maxBytes: input.maxBytes,
604 + });
605 + if (signal.aborted) {
606 + await removePersistedComposerAttachmentFile(attachment.fileUri);
607 + signal.throwIfAborted();
608 + }
609 + // Rejected attachments are cleaned up by the draft store.
610 + if (appendComposerDraftAttachments(input.draftKey, [attachment], { appendReference: true }))
611 + throw new Error("This message already has as many attachments as it can hold.");
612 + } finally {
613 + file.dispose();
614 + }
615 +}
616 +
617 +type EntryContent =
618 + | { readonly status: "loading" }
619 + | { readonly status: "text"; readonly text: string; readonly truncated: boolean }
620 + | { readonly status: "file"; readonly uri: string }
621 + | { readonly status: "failed"; readonly title: string; readonly message: string };
622 +
623 +function ZipEntryView(props: {
624 + readonly archiveName: string;
625 + readonly entry: ZipEntry;
626 + readonly environmentId: EnvironmentId | null;
627 + readonly draftKey: string | null;
628 + readonly maxAttachmentBytes: number | undefined;
629 + readonly onBack: () => void;
630 +}) {
631 + const { entry, draftKey, maxAttachmentBytes } = props;
632 + const { mimeType } = entry;
633 + const previewKind = filePreviewKind({ name: entry.name, mimeType });
634 + const isText = previewKind === "text" || previewKind === "markdown" || previewKind === "html";
635 + // Archive HTML is shown as source: a rendered page could load its sibling files.
636 + const kind = previewKind === "html" ? "text" : previewKind;
637 + const viewerKind = isText || kind === "audio" ? null : (nativeViewerKind(kind) ?? "document");
638 + const tooBig = entry.sizeBytes > ARCHIVE_ENTRY_MAX_BYTES;
639 + const [content, setContent] = useState<EntryContent>(
640 + tooBig
641 + ? {
642 + status: "failed",
643 + title: "Too big to preview",
644 + message: `Previews stop at ${formatAttachmentSize(ARCHIVE_ENTRY_MAX_BYTES)}. Save the file to open it in another app.`,
645 + }
646 + : { status: "loading" },
647 + );
648 + const [rendered, setRendered] = useState(true);
649 + const [revision, setRevision] = useState(0);
650 + const [viewerOpen, setViewerOpen] = useState(true);
651 + const [viewerError, setViewerError] = useState<string | null>(null);
652 + const [busy, setBusy] = useState<"save" | "attach" | null>(null);
653 + const action = useRef<AbortController | null>(null);
654 + const pendingViewerError = useRef<string | null>(null);
655 + // oxlint-disable-next-line t3code/react-effect-budget -- Cancel a pending save or attach when the entry closes.
656 + useEffect(() => () => action.current?.abort(), []);
657 + // oxlint-disable-next-line t3code/react-effect-budget -- Write the selected entry to a cached file and release it on cleanup.
658 + useEffect(() => {
659 + if (tooBig) return;
660 + const controller = new AbortController();
661 + let release: (() => void) | undefined;
662 + void (async (): Promise<EntryContent> => {
663 + if (isText) return { status: "text", ...decodeFilePreviewText(entry.bytes) };
664 + const file = await writeGeneratedAttachmentFile({
665 + bytes: entry.bytes,
666 + attachment: { name: entry.name, mimeType },
667 + });
668 + if (controller.signal.aborted) {
669 + file.dispose();
670 + controller.signal.throwIfAborted();
671 + }
672 + release = file.dispose;
673 + return { status: "file", uri: file.uri };
674 + })()
675 + .then((value) => {
676 + if (!controller.signal.aborted) setContent(value);
677 + })
678 + .catch((cause: unknown) => {
679 + if (!controller.signal.aborted)
680 + setContent({
681 + status: "failed",
682 + title: "Couldn't read this file",
683 + message: errorMessage(cause, "Could not read this file."),
684 + });
685 + });
686 + return () => {
687 + controller.abort();
688 + release?.();
689 + };
690 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reread the entry.
691 + }, [entry, isText, mimeType, tooBig, revision]);
692 +
693 + const run = (kind: "save" | "attach", task: (signal: AbortSignal) => Promise<unknown>) => {
694 + if (busy) return;
695 + setBusy(kind);
696 + const controller = new AbortController();
697 + action.current = controller;
698 + void task(controller.signal).then(
699 + () => {
700 + if (controller.signal.aborted) return;
701 + setBusy(null);
702 + if (kind === "attach")
703 + Dialog.alert("Added to chat", `${entry.name} is attached to your message.`);
704 + },
705 + (cause: unknown) => {
706 + if (controller.signal.aborted) return;
707 + setBusy(null);
708 + Dialog.alert(
709 + kind === "save" ? "Could not save file" : "Could not add file to chat",
710 + errorMessage(cause, "Please try again."),
711 + );
712 + },
713 + );
714 + };
715 + const save = () =>
716 + run("save", (signal) =>
717 + shareGeneratedAttachment({
718 + bytes: entry.bytes,
719 + attachment: { name: entry.name, mimeType },
720 + signal,
721 + }),
722 + );
723 + const canAddToChat = draftKey !== null && maxAttachmentBytes !== undefined;
724 + const addToChat = () => {
725 + if (draftKey === null || maxAttachmentBytes === undefined) return;
726 + run("attach", (signal) =>
727 + addZipEntryToDraft({ entry, draftKey, maxBytes: maxAttachmentBytes, signal }),
728 + );
729 + };
730 + const openViewer = () => {
731 + setViewerError(null);
732 + setViewerOpen(true);
733 + };
734 +
735 + const text = content.status === "text" ? content : null;
736 + const delimiter = filePreviewDelimiter({ name: entry.name, mimeType });
737 + const table = text && delimiter ? parseDelimitedPreview(text.text, delimiter) : null;
738 + const uri = content.status === "file" ? content.uri : null;
739 + const { renderedMode, activeMode } = attachmentDocumentPresentation({
740 + kind,
741 + hasTable: table !== null,
742 + hasEnvironment: props.environmentId !== null,
743 + rendered,
744 + });
745 + const folders = entry.path.split("/").slice(0, -1);
746 + const subtitle = `${[props.archiveName, ...folders].join(" / ")} · ${formatAttachmentSize(entry.sizeBytes)}`;
747 + const isAndroid = Platform.OS === "android";
748 + return (
749 + <View className="flex-1 bg-sheet">
750 + <NativeStackScreenOptions
751 + options={{
752 + headerShown: !isAndroid,
753 + headerTitle: entry.name,
754 + title: entry.name,
755 + unstable_headerSubtitle: isAndroid ? undefined : subtitle,
756 + }}
757 + />
758 + {isAndroid ? (
759 + <AndroidScreenHeader
760 + title={entry.name}
761 + subtitle={subtitle}
762 + onBack={props.onBack}
763 + actions={[
764 + ...(renderedMode
765 + ? [
766 + {
767 + accessibilityLabel: rendered ? "Show source" : "Show preview",
768 + icon: rendered ? ("doc.text" as const) : ("eye" as const),
769 + onPress: () => setRendered((value) => !value),
770 + },
771 + ]
772 + : []),
773 + ...(canAddToChat
774 + ? [
775 + {
776 + accessibilityLabel: "Add to chat",
777 + icon: "plus.bubble" as const,
778 + onPress: addToChat,
779 + disabled: busy !== null,
780 + },
781 + ]
782 + : []),
783 + {
784 + accessibilityLabel: "Save file",
785 + icon: "square.and.arrow.up",
786 + onPress: save,
787 + loading: busy === "save",
788 + },
789 + ]}
790 + />
791 + ) : (
792 + <Toolbar placement="right">
793 + <Toolbar.Menu accessibilityLabel="File actions" icon="ellipsis">
794 + {renderedMode ? (
795 + <Toolbar.MenuAction
796 + icon={rendered ? "doc.text" : "eye"}
797 + onPress={() => setRendered((value) => !value)}
798 + >
799 + {rendered ? "Show source" : "Show preview"}
800 + </Toolbar.MenuAction>
801 + ) : null}
802 + {canAddToChat ? (
803 + <Toolbar.MenuAction icon="plus.bubble" disabled={busy !== null} onPress={addToChat}>
804 + Add to chat
805 + </Toolbar.MenuAction>
806 + ) : null}
807 + <Toolbar.MenuAction icon="square.and.arrow.up" disabled={busy !== null} onPress={save}>
808 + Save file
809 + </Toolbar.MenuAction>
810 + </Toolbar.Menu>
811 + </Toolbar>
812 + )}
813 + {content.status === "failed" ? (
814 + <ScrollView contentContainerClassName="flex-grow items-center justify-center px-6">
815 + <EmptyState
816 + variant="plain"
817 + title={content.title}
818 + detail={content.message}
819 + action={
820 + <Button tone="primary" label="Save file" loading={busy === "save"} onPress={save} />
821 + }
822 + />
823 + </ScrollView>
824 + ) : viewerKind && uri && !viewerOpen ? (
825 + // Closing the viewer stays here so Save and Add to chat remain reachable.
826 + <View className="flex-1 items-center justify-center bg-sheet px-6">
827 + <EmptyState
828 + title={viewerError ? "No preview for this file" : entry.name}
829 + detail={viewerError ?? "Open it in the file viewer, save it, or add it to chat."}
830 + actionLabel="Open in file viewer"
831 + onAction={openViewer}
832 + />
833 + </View>
834 + ) : (
835 + <AttachmentDocumentBody
836 + document={{
837 + kind,
838 + activeMode,
839 + uri,
840 + content: text,
841 + table,
842 + error: null,
843 + needsText: isText,
844 + retry: () => setRevision((value) => value + 1),
845 + revision,
846 + }}
847 + name={entry.name}
848 + environmentId={props.environmentId}
849 + htmlRender={false}
850 + nativeViewer={viewerKind ? (uri ? "open" : "pending") : null}
851 + nativeError={null}
852 + onOpenNative={openViewer}
853 + />
854 + )}
855 + {viewerKind && uri && viewerOpen ? (
856 + <FilePreviewModal
857 + source={{ kind: viewerKind, name: entry.name, mimeType, uri }}
858 + onOpenError={(error) => {
859 + pendingViewerError.current = nativeViewerErrorMessage(error);
860 + }}
861 + onRequestClose={() => {
862 + setViewerError(pendingViewerError.current);
863 + pendingViewerError.current = null;
864 + setViewerOpen(false);
865 + }}
866 + />
867 + ) : null}
868 + </View>
869 + );
870 +}
apps/mobile/src/features/files/zipTree.ts new
+139
@@ -0,0 +1,139 @@
1 +export interface ZipEntry {
2 + readonly path: string;
3 + readonly name: string;
4 + readonly isDirectory: boolean;
5 + readonly sizeBytes: number;
6 + readonly mimeType: string;
7 + readonly bytes: Uint8Array<ArrayBuffer>;
8 +}
9 +
10 +export interface ZipTreeNode {
11 + readonly path: string;
12 + readonly label: string;
13 + readonly entry: ZipEntry | null;
14 + readonly children: ReadonlyArray<ZipTreeNode>;
15 + readonly fileCount: number;
16 +}
17 +
18 +export interface ZipTreeRow {
19 + readonly node: ZipTreeNode;
20 + readonly depth: number;
21 +}
22 +
23 +interface MutableNode {
24 + path: string;
25 + name: string;
26 + entry: ZipEntry | null;
27 + children: Map<string, MutableNode>;
28 +}
29 +
30 +const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
31 +
32 +function freeze(node: MutableNode): ZipTreeNode {
33 + let current = node;
34 + let label = node.name;
35 + while (current.path !== "" && current.entry === null && current.children.size === 1) {
36 + const [only] = current.children.values();
37 + if (!only || only.entry !== null) break;
38 + current = only;
39 + label = `${label}/${only.name}`;
40 + }
41 + const children = [...current.children.values()]
42 + .sort((left, right) =>
43 + (left.entry === null) !== (right.entry === null)
44 + ? left.entry === null
45 + ? -1
46 + : 1
47 + : collator.compare(left.name, right.name),
48 + )
49 + .map(freeze);
50 + return {
51 + path: current.path,
52 + label,
53 + entry: current.entry,
54 + children,
55 + fileCount:
56 + current.entry === null ? children.reduce((sum, child) => sum + child.fileCount, 0) : 1,
57 + };
58 +}
59 +
60 +export function buildZipTree(entries: ReadonlyArray<ZipEntry>): ReadonlyArray<ZipTreeNode> {
61 + const root: MutableNode = { path: "", name: "", entry: null, children: new Map() };
62 + for (const entry of entries) {
63 + const parts = entry.path.split("/").filter(Boolean);
64 + let current = root;
65 + parts.forEach((part, index) => {
66 + const leaf = index === parts.length - 1 && !entry.isDirectory;
67 + const key = leaf ? part : `${part}/`;
68 + let child = current.children.get(key);
69 + if (!child) {
70 + child = {
71 + path: parts.slice(0, index + 1).join("/"),
72 + name: part,
73 + entry: leaf ? entry : null,
74 + children: new Map(),
75 + };
76 + current.children.set(key, child);
77 + }
78 + current = child;
79 + });
80 + }
81 + return freeze(root).children;
82 +}
83 +
84 +function flatten(
85 + output: ZipTreeRow[],
86 + node: ZipTreeNode,
87 + depth: number,
88 + collapsed: ReadonlySet<string>,
89 + query: string,
90 +): boolean {
91 + if (node.entry) {
92 + if (query && !node.entry.path.toLowerCase().includes(query)) return false;
93 + output.push({ node, depth });
94 + return true;
95 + }
96 + const children: ZipTreeRow[] = [];
97 + let visible = !query;
98 + if (query || !collapsed.has(node.path)) {
99 + for (const child of node.children) {
100 + if (flatten(children, child, depth + 1, collapsed, query)) visible = true;
101 + }
102 + }
103 + if (!visible) return false;
104 + output.push({ node, depth }, ...children);
105 + return true;
106 +}
107 +
108 +export function flattenZipTree(
109 + nodes: ReadonlyArray<ZipTreeNode>,
110 + collapsed: ReadonlySet<string>,
111 + query: string,
112 +): ReadonlyArray<ZipTreeRow> {
113 + const output: ZipTreeRow[] = [];
114 + const normalized = query.trim().toLowerCase();
115 + for (const node of nodes) flatten(output, node, 0, collapsed, normalized);
116 + return output;
117 +}
118 +
119 +export function zipFolderLabel(label: string) {
120 + const parts = label.split("/");
121 + const name = parts.at(-1) ?? label;
122 + if (parts.length > 3) return { prefix: `${parts[0]}/…/${parts.at(-2)}/`, name };
123 + return { prefix: parts.length > 1 ? `${parts.slice(0, -1).join("/")}/` : "", name };
124 +}
125 +
126 +export function zipDownloadTimeLeft(input: {
127 + readonly receivedBytes: number;
128 + readonly totalBytes: number;
129 + readonly elapsedMs: number;
130 +}) {
131 + if (input.receivedBytes <= 0 || input.totalBytes <= input.receivedBytes || input.elapsedMs < 1000)
132 + return null;
133 + const seconds = Math.ceil(
134 + ((input.totalBytes - input.receivedBytes) * input.elapsedMs) / input.receivedBytes / 1000,
135 + );
136 + return seconds < 60
137 + ? `About ${seconds} ${seconds === 1 ? "second" : "seconds"} left`
138 + : `About ${Math.ceil(seconds / 60)} minutes left`;
139 +}
apps/mobile/src/lib/attachmentDownload.ts
+14
@@ -271,6 +271,20 @@ export async function shareLocalAttachment(input: {
271 }
272 }
273
274 +export async function writeGeneratedAttachmentFile(input: {
275 + readonly bytes: Uint8Array;
276 + readonly attachment: AttachmentFileMetadata;
277 +}): Promise<AttachmentPreviewFile> {
278 + const cached = await createCachedAttachmentFile(input.attachment);
279 + try {
280 + await cached.file.write(input.bytes);
281 + return cached.preview;
282 + } catch (error) {
283 + cached.preview.dispose();
284 + throw error;
285 + }
286 +}
287 +
288 export async function shareGeneratedAttachment(input: {
289 readonly bytes: Uint8Array;
290 readonly attachment: AttachmentFileMetadata;
apps/mobile/src/lib/composerImages.ts
+1 -1
@@ -220,7 +220,7 @@ export async function removePersistedComposerAttachmentFile(uri: string): Promis
220 }
221 }
222
223 -async function createComposerFileAttachment(input: {
223 +export async function createComposerFileAttachment(input: {
224 readonly uri: string;
225 readonly name: string;
226 readonly mimeType: string;
apps/mobile/vite.config.ts
+1
@@ -14,6 +14,7 @@ const reactTests = [
14 "src/features/pull-requests/usePullRequestDiff.test.tsx",
15 "src/components/ProjectFavicon.test.tsx",
16 "src/components/ui/Dialog.android.test.tsx",
17 + "src/features/files/ZipArchiveView.test.tsx",
18 "src/features/pull-requests/guide/useReviewGuide.test.tsx",
19 "src/features/settings/SettingsServerControlsRouteScreen.test.tsx",
20 "src/features/settings/components/BranchNamingSettings.test.tsx",
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+1 -1
@@ -47,7 +47,7 @@ import VirtualTablePreview from "./VirtualTablePreview";
47 import { OfficeFilePreview } from "./OfficeFilePreview";
48 import { MermaidFilePreview } from "./MermaidFilePreview";
49 import JSZip from "jszip";
50 -import { boundedZip } from "./boundedZip";
50 +import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip";
51 import BinaryViewer from "./BinaryViewer";
52 import { decodeImagePreview } from "./decodeImagePreview";
53 import type { BinaryWorkerResult } from "./binaryPreviewProtocol";
apps/web/src/components/files/binaryPreview.worker.ts
+1 -1
@@ -1,6 +1,6 @@
1 import type { Database } from "sql.js";
2
3 -import { boundedZip } from "./boundedZip";
3 +import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip";
4 import {
5 ARCHIVE_ENTRY_MAX_BYTES,
6 ARCHIVE_MAX_ENTRIES,
apps/web/src/components/files/binaryPreviewProtocol.ts
+8 -4
@@ -1,7 +1,11 @@
1 -export const BINARY_PREVIEW_MAX_BYTES = 50 * 1024 * 1024;
2 -export const ARCHIVE_ENTRY_MAX_BYTES = 10 * 1024 * 1024;
3 -export const ARCHIVE_MAX_ENTRIES = 2048;
4 -export const ARCHIVE_MAX_RATIO = 200;
1 +import { ARCHIVE_MAX_BYTES } from "@t3tools/client-runtime/zip/bounded-zip";
2 +
3 +export {
4 + ARCHIVE_ENTRY_MAX_BYTES,
5 + ARCHIVE_MAX_ENTRIES,
6 + ARCHIVE_MAX_RATIO,
7 +} from "@t3tools/client-runtime/zip/bounded-zip";
8 +export const BINARY_PREVIEW_MAX_BYTES = ARCHIVE_MAX_BYTES;
9 export const SQLITE_PAGE_SIZE = 50;
10
11 export interface ArchiveEntry {
apps/web/src/components/files/officeArchive.ts
+1 -1
@@ -1,5 +1,5 @@
1 import JSZip from "jszip";
2 -import { checkZipDirectory } from "./zipDirectory";
2 +import { checkZipDirectory } from "@t3tools/client-runtime/zip/directory";
3 import { SaxesParser } from "saxes";
4 import { externalUrl } from "./office/links";
5
docs/user/composer.md
+3 -1
@@ -323,7 +323,9 @@ file: a header row with the view toggle, **Copy contents** and **Save file**. On
323 open in the same file screen as workspace files; its menu holds **Copy contents**, **Save or
324 share** and **Open in file viewer**. Pictures, videos and PDFs keep their native viewers, and
325 other document formats such as Word or Pages open in the device's own viewer when it has one.
326 -If nothing on the device can show a format, save or share it to open it elsewhere.
326 +If nothing on the device can show a format, save or share it to open it elsewhere. A ZIP up to
327 +50 MB opens as a folder list on every surface; on mobile, select a file inside it to preview,
328 +save, or add it to chat.
329
330 ## Images and videos in messages
331
packages/client-runtime/package.json
+9
@@ -3,6 +3,14 @@
3 "private": true,
4 "type": "module",
5 "exports": {
6 + "./zip/bounded-zip": {
7 + "types": "./src/zip/boundedZip.ts",
8 + "default": "./src/zip/boundedZip.ts"
9 + },
10 + "./zip/directory": {
11 + "types": "./src/zip/zipDirectory.ts",
12 + "default": "./src/zip/zipDirectory.ts"
13 + },
14 "./workspace-basename-lookup": {
15 "types": "./src/workspaceBasenameLookup.ts",
16 "default": "./src/workspaceBasenameLookup.ts"
@@ -515,6 +523,7 @@
523 "@t3tools/source-control-core": "workspace:*",
524 "@t3tools/source-control-definitions": "workspace:*",
525 "effect": "catalog:",
526 + "jszip": "3.10.1",
527 "three": "0.180.0"
528 },
529 "devDependencies": {
packages/client-runtime/src/zip/boundedZip.ts renamed
+8 -9
@@ -1,15 +1,14 @@
1 import JSZip from "jszip";
2 -import { checkZipDirectory } from "./zipDirectory";
2 +import { checkZipDirectory } from "./zipDirectory.ts";
3
4 -import {
5 - ARCHIVE_MAX_ENTRIES,
6 - ARCHIVE_MAX_RATIO,
7 - BINARY_PREVIEW_MAX_BYTES,
8 -} from "./binaryPreviewProtocol";
4 +export const ARCHIVE_MAX_BYTES = 50 * 1024 * 1024;
5 +export const ARCHIVE_ENTRY_MAX_BYTES = 10 * 1024 * 1024;
6 +export const ARCHIVE_MAX_ENTRIES = 2048;
7 +export const ARCHIVE_MAX_RATIO = 200;
8
9 export async function boundedZip(
10 bytes: ArrayBuffer,
12 - entryLimit = BINARY_PREVIEW_MAX_BYTES,
11 + entryLimit = ARCHIVE_MAX_BYTES,
12 limits: {
13 totalLimit?: number;
14 xmlLimit?: number;
@@ -17,7 +16,7 @@ export async function boundedZip(
16 markupLimit?: number;
17 } = {},
18 ) {
20 - if (bytes.byteLength > BINARY_PREVIEW_MAX_BYTES)
19 + if (bytes.byteLength > ARCHIVE_MAX_BYTES)
20 throw new Error("Preview limited to files under 50 MB.");
21 checkZipDirectory(bytes, ARCHIVE_MAX_ENTRIES);
22 const zip = await JSZip.loadAsync(bytes);
@@ -49,7 +48,7 @@ export async function boundedZip(
48 for (const byte of chunk) if (byte === 0x3c) markup++;
49 if (
50 markup > (limits.markupLimit ?? Infinity) ||
52 - total > (limits.totalLimit ?? BINARY_PREVIEW_MAX_BYTES) ||
51 + total > (limits.totalLimit ?? ARCHIVE_MAX_BYTES) ||
52 total >
53 Math.max(limits.ratioFloor ?? 0, Math.max(1, bytes.byteLength) * ARCHIVE_MAX_RATIO) ||
54 length > entryLimit ||
packages/client-runtime/src/zip/zipDirectory.ts renamed
pnpm-lock.yaml
+3
@@ -1473,6 +1473,9 @@ importers:
1473 effect:
1474 specifier: 4.0.5
1475 version: 4.0.5
1476 + jszip:
1477 + specifier: 3.10.1
1478 + version: 3.10.1
1479 three:
1480 specifier: 0.180.0
1481 version: 0.180.0