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("../../native/NativeScrollViewMarker", () => ({ NativeScrollView: () => null }));
106vi.mock("../../components/ui/AppBar", () => {
107 interface Item {
108 readonly id: string;
109 readonly title?: string;
110 readonly disabled?: boolean;
111 readonly onPress?: () => void;
112 readonly items?: ReadonlyArray<Item>;
113 }
114 const renderItems = (items: ReadonlyArray<Item>): ReactNode =>
115 items.map((item) =>
116 item.items ? (
117 renderItems(item.items)
118 ) : (
119 <button key={item.id} disabled={item.disabled} onClick={item.onPress}>
120 {item.title}
121 </button>
122 ),
123 );
124 return {
125 AppBar: (props: {
126 readonly menus?: ReadonlyArray<{ readonly items: ReadonlyArray<Item> }>;
127 }) => <div>{props.menus?.map((menu) => renderItems(menu.items))}</div>,
128 };
129});
130vi.mock("../../components/ui/useBarInset", () => ({
131 useContentTopInset: () => 0,
132 useContentBottomInset: () => 0,
133}));
134vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
135vi.mock("../../components/ui/Progress", () => ({ Progress: () => null }));
136vi.mock("../../components/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
137vi.mock("../../components/ui/FilePreviewModal", () => ({ FilePreviewModal: () => null }));
138vi.mock("../../lib/copyTextWithHaptic", () => ({}));
139vi.mock("./SourceFileSurface", () => ({
140 SourceFileSurface: (props: { readonly contents: string }) => <pre>{props.contents}</pre>,
141}));
142vi.mock("./AudioFilePreview", () => ({ AudioFilePreview: () => null }));
143vi.mock("./EpubFilePreview", () => ({ EpubFilePreview: () => null }));
144vi.mock("./FileMarkdownPreview", () => ({ FileMarkdownPreview: () => null }));
145vi.mock("./WorkspaceFileWebPreview", () => ({ WorkspaceFileWebPreview: () => null }));
146vi.mock("../threads/HtmlRenderWebView", () => ({ HtmlRenderWebView: () => null }));
147vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
148 useAppearancePreferences: () => ({
149 appearance: { codeWordBreak: false },
150 themeVariables: { "--color-icon": "#000000" },
151 setCodeWordBreak: () => {},
152 }),
153}));
154
155import { ZipArchiveView } from "./ZipArchiveView";
156import { AttachmentFileScreen } from "./AttachmentFileScreen";
157import { appAtomRegistry } from "../../state/atom-registry";
158import { composerDraftsAtom } from "../../state/use-composer-drafts";
159
160function setup() {
161 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
162 // boundedZip yields on setTimeout once a slow runner spends 50ms reading, so settle drives both.
163 vi.useFakeTimers({ toFake: ["setImmediate", "clearImmediate", "setTimeout", "clearTimeout"] });
164 files.clear();
165 navigation.remove = null;
166 server.capabilities = { repositoryIdentity: false };
167 server.refresh.mockClear();
168 appAtomRegistry.set(composerDraftsAtom, {});
169 files.set(
170 "file:///first.zip",
171 Uint8Array.from(
172 atob(
173 "UEsDBBQAAAAAAAAAIVyzyFShFgAAABYAAAAJAAAAZmlyc3QudHh0Rmlyc3QgYXJjaGl2ZSBjb250ZW50c1BLAQIUAxQAAAAAAAAAIVyzyFShFgAAABYAAAAJAAAAAAAAAAAAAACAAQAAAABmaXJzdC50eHRQSwUGAAAAAAEAAQA3AAAAPQAAAAAA",
174 ),
175 (character) => character.charCodeAt(0),
176 ),
177 );
178
179 const container = document.createElement("div");
180 const root = createRoot(container);
181 onTestFinished(() => {
182 act(() => root.unmount());
183 files.clear();
184 vi.useRealTimers();
185 vi.unstubAllGlobals();
186 });
187 const props: ComponentProps<typeof ZipArchiveView> = {
188 name: "archive.zip",
189 subtitle: "ZIP",
190 sizeBytes: 0,
191 uri: "file:///first.zip",
192 isLocal: true,
193 refresh: async () => null,
194 environmentId: null,
195 draftKey: null,
196 maxAttachmentBytes: undefined,
197 onSave: () => {},
198 onRemove: null,
199 };
200 return {
201 container,
202 root,
203 props,
204 render: async (input = props) => {
205 await act(async () => root.render(<ZipArchiveView {...input} />));
206 },
207 settle: async (assert: () => void) => {
208 await act(async () => vi.runAllTimersAsync());
209 assert();
210 },
211 };
212}
213
214it("opens a ZIP chat attachment as a browsable archive on the attachment file screen", async () => {
215 const screen = setup();
216 server.capabilities = {
217 repositoryIdentity: false,
218 attachmentUploads: true,
219 fileAttachments: { maxUploadBytes: 1024 },
220 };
221 const { fetch } = await import("expo/fetch");
222 vi.mocked(fetch, { partial: true }).mockImplementation(async () => ({
223 ok: true,
224 body: new Response(Uint8Array.from(files.get("file:///first.zip")!)).body,
225 }));
226 await act(async () =>
227 screen.root.render(
228 <AttachmentFileScreen
229 route={{
230 params: {
231 environmentId: "environment-1",
232 threadId: "thread-1",
233 attachmentId: "attachment-1",
234 name: "archive.zip",
235 mimeType: "application/zip",
236 sizeBytes: "200",
237 },
238 }}
239 />,
240 ),
241 );
242 await screen.settle(() =>
243 expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull(),
244 );
245 await act(async () =>
246 screen.container.querySelector<HTMLButtonElement>('[aria-label="first.txt"]')!.click(),
247 );
248 await screen.settle(() =>
249 expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
250 );
251 const add = Array.from(screen.container.querySelectorAll("button")).find(
252 (button) => button.textContent === "Add to chat",
253 );
254 expect(add?.disabled).toBe(false);
255});
256
257it("keeps the ZIP filter and archive open when native Back closes a selected entry", async () => {
258 const screen = setup();
259 await screen.render();
260 await screen.settle(() =>
261 expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull(),
262 );
263 const filter = screen.container.querySelector<HTMLInputElement>(
264 '[aria-label="Filter files in ZIP"]',
265 )!;
266 await act(async () => {
267 Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(
268 filter,
269 "first",
270 );
271 filter.dispatchEvent(new Event("input", { bubbles: true }));
272 });
273 await act(async () =>
274 screen.container.querySelector<HTMLButtonElement>('[aria-label="first.txt"]')!.click(),
275 );
276 await screen.settle(() =>
277 expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
278 );
279
280 expect(navigation.remove).not.toBeNull();
281 await act(async () => navigation.remove!());
282
283 expect(screen.container.querySelector("pre")).toBeNull();
284 expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull();
285 expect(
286 screen.container.querySelector<HTMLInputElement>('[aria-label="Filter files in ZIP"]')?.value,
287 ).toBe("first");
288});
289
290it("asks for a password before browsing encrypted entries", async () => {
291 const screen = setup();
292 const bytes = files.get("file:///first.zip")!;
293 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
294 const directory = view.getUint32(bytes.length - 6, true);
295 view.setUint16(directory + 8, view.getUint16(directory + 8, true) | 1, true);
296 await screen.render();
297 await screen.settle(() =>
298 expect(screen.container.textContent).toContain("This file requires a password."),
299 );
300 expect(screen.container.querySelector('[aria-label="first.txt"]')).toBeNull();
301});
302
303it("keeps the archive and selected entry when the parent re-renders with a new refresh", async () => {
304 const screen = setup();
305 await screen.render();
306 await screen.settle(() =>
307 expect(screen.container.querySelector('[aria-label="first.txt"]')).not.toBeNull(),
308 );
309 await act(async () =>
310 screen.container.querySelector<HTMLButtonElement>('[aria-label="first.txt"]')!.click(),
311 );
312 await screen.settle(() =>
313 expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
314 );
315 files.delete("file:///first.zip");
316
317 await screen.render({ ...screen.props, refresh: async () => null });
318 await screen.settle(() =>
319 expect(screen.container.querySelector("pre")?.textContent).toBe("First archive contents"),
320 );
321 expect(navigation.remove).not.toBeNull();
322});