Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ZipArchiveView.test.tsx

315 lines10.9 KB

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", () => ({ useContentTopInset: () => 0 }));
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 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 };
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});