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