Open History to see the last commit
1import { AsyncResult } from "effect/reactivity";
2import { act, type ComponentProps, type ReactNode } from "react";
3import { createRoot } from "react-dom/client";
4import { expect, it, onTestFinished, vi } from "vite-plus/test";
5import type { ServerConfig } from "@t3tools/contracts";
6
7import type { ZipTreeRow } from "./zipTree";
8
9const files = vi.hoisted(() => new Map<string, Uint8Array>());
10const navigation = vi.hoisted(() => ({ remove: null as (() => void) | null }));
11const server = vi.hoisted(() => ({
12 capabilities: { repositoryIdentity: false } as ServerConfig["environment"]["capabilities"],
13 refresh: vi.fn(async () => "file:///first.zip"),
14}));
15
16vi.mock("../../state/entities", () => ({
17 useEnvironmentServerConfig: () => ({ environment: { capabilities: server.capabilities } }),
18}));
19vi.mock("../../state/assets", () => ({
20 useRefreshAssetUrl: () => server.refresh,
21 useFreshAssetUrl: () => AsyncResult.success({ url: "file:///first.zip", authorizedAt: 0 }),
22}));
23
24vi.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});
60vi.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}));
77vi.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}));
97vi.mock("expo/fetch", () => ({ fetch: vi.fn() }));
98vi.mock("expo-crypto", () => ({ randomUUID: vi.fn() }));
99vi.mock("@react-navigation/native", () => ({
100 useNavigation: () => ({ canGoBack: () => false }),
101 usePreventRemove: (enabled: boolean, remove: () => void) => {
102 navigation.remove = enabled ? remove : null;
103 },
104}));
105vi.mock("react-native-safe-area-context", () => ({
106 useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
107}));
108vi.mock("../../native/NativeScrollViewMarker", () => ({ NativeScrollView: () => null }));
109vi.mock("../../native/StackHeader", () => ({ NativeStackScreenOptions: () => null }));
110vi.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});
128vi.mock("../../components/ui/AndroidScreenHeader", () => ({ AndroidScreenHeader: () => null }));
129vi.mock("../../components/ui/Menu", () => ({ Menu: () => null }));
130vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
131vi.mock("../../components/ui/Progress", () => ({ Progress: () => null }));
132vi.mock("../../components/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
133vi.mock("../../components/FilePreviewModal", () => ({ FilePreviewModal: () => null }));
134vi.mock("../../lib/copyTextWithHaptic", () => ({}));
135vi.mock("./SourceFileSurface", () => ({
136 SourceFileSurface: (props: { readonly contents: string }) => <pre>{props.contents}</pre>,
137}));
138vi.mock("./AudioFilePreview", () => ({ AudioFilePreview: () => null }));
139vi.mock("./FileMarkdownPreview", () => ({ FileMarkdownPreview: () => null }));
140vi.mock("./WorkspaceFileWebPreview", () => ({ WorkspaceFileWebPreview: () => null }));
141vi.mock("../threads/HtmlRenderWebView", () => ({ HtmlRenderWebView: () => null }));
142vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
143 useAppearancePreferences: () => ({
144 appearance: { codeWordBreak: false },
145 themeVariables: { "--color-icon": "#000000" },
146 setCodeWordBreak: () => {},
147 }),
148}));
149
150import { ZipArchiveView } from "./ZipArchiveView";
151import { AttachmentFileScreen } from "./AttachmentFileScreen";
152import { appAtomRegistry } from "../../state/atom-registry";
153import { composerDraftsAtom } from "../../state/use-composer-drafts";
154
155function 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
209it("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
252it("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
285it("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
296it("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});