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

composerImages.test.ts

286 lines9.3 KB

1import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2import {
3 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
4 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
5} from "@t3tools/contracts";
6​
7const files = new Map<
8 string,
9 { base64: string; deleted: boolean; text?: string; mimeType?: string }
10>();
11​
12const manipulator = vi.hoisted(() => {
13 const state = { sourceSize: { width: 0, height: 0 }, renderedBase64: "cmVuZGVyZWQ=" };
14 const manipulate = vi.fn((source: string | { width: number; height: number }) => {
15 let size = typeof source === "string" ? state.sourceSize : source;
16 const context = {
17 resize: vi.fn((next: { width: number; height: number }) => {
18 size = next;
19 return context;
20 }),
21 renderAsync: vi.fn(async () => ({
22 ...size,
23 release: vi.fn(),
24 saveAsync: vi.fn(async (options: { format: string }) => {
25 const uri = `file:///cache/rendered.${options.format}`;
26 files.set(uri, { base64: state.renderedBase64, deleted: false });
27 return { uri, base64: state.renderedBase64 };
28 }),
29 })),
30 };
31 return context;
32 });
33 return { state, manipulate };
34});
35​
36vi.mock("expo-image-manipulator", () => ({
37 ImageManipulator: { manipulate: manipulator.manipulate },
38 SaveFormat: { JPEG: "jpeg", PNG: "png" },
39}));
40​
41vi.mock("expo-file-system", () => ({
42 File: class {
43 readonly uri: string;
44 readonly name: string;
45 readonly parentDirectory: { readonly uri: string };
46​
47 constructor(parent: string | { readonly uri: string }, name?: string) {
48 const parentUri = typeof parent === "string" ? parent : parent.uri;
49 this.uri = name ? `${parentUri}/${name}` : parentUri;
50 this.name = name ?? this.uri.split("/").at(-1) ?? "file";
51 this.parentDirectory = { uri: this.uri.slice(0, -(this.name.length + 1)) };
52 }
53​
54 get exists(): boolean {
55 return files.has(this.uri) && files.get(this.uri)?.deleted === false;
56 }
57​
58 get type(): string {
59 return files.get(this.uri)?.mimeType ?? "";
60 }
61​
62 get size(): number | null {
63 const entry = files.get(this.uri);
64 return entry && !entry.deleted
65 ? Math.floor((entry.base64.replace(/=+$/, "").length * 3) / 4)
66 : null;
67 }
68​
69 async copy(destination: { readonly uri: string }): Promise<void> {
70 const entry = files.get(this.uri);
71 if (!entry) throw new Error("missing file");
72 files.set(destination.uri, { ...entry });
73 }
74​
75 async base64(): Promise<string> {
76 const entry = files.get(this.uri);
77 if (!entry || entry.deleted) {
78 throw new Error("missing file");
79 }
80 return entry.base64;
81 }
82​
83 delete(): void {
84 const entry = files.get(this.uri);
85 if (entry) {
86 entry.deleted = true;
87 }
88 }
89​
90 create(): void {
91 files.set(this.uri, { base64: "", deleted: false });
92 }
93​
94 write(text: string): void {
95 files.set(this.uri, { base64: "", deleted: false, text });
96 }
97​
98 moveSync(destination: { readonly uri: string }): void {
99 const entry = files.get(this.uri);
100 if (!entry) throw new Error("missing staged file");
101 files.set(destination.uri, entry);
102 files.delete(this.uri);
103 }
104 },
105 Directory: class {
106 readonly uri: string;
107​
108 constructor(parent: string, name: string) {
109 this.uri = `${parent}/${name}`;
110 }
111​
112 create(): void {}
113 },
114 FileMode: { ReadOnly: "r", WriteOnly: "w" },
115 Paths: { document: "file:///documents" },
116}));
117​
118vi.mock("./uuid", () => ({
119 uuidv4: () => "attachment-id",
120}));
121​
122import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages";
123​
124describe("native pasted image cleanup", () => {
125 beforeEach(() => {
126 files.clear();
127 manipulator.state.renderedBase64 = "cmVuZGVyZWQ=";
128 });
129​
130 it("preserves the reported image type of extensionless Android content URIs", async () => {
131 const uri = "content://media/external/images/media/42";
132 files.set(uri, { base64: "aGVsbG8=", deleted: false, mimeType: "image/jpeg" });
133​
134 const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
135​
136 expect(attachments).toEqual([
137 expect.objectContaining({
138 name: "pasted-image.jpeg",
139 mimeType: "image/jpeg",
140 dataUrl: "data:image/jpeg;base64,aGVsbG8=",
141 previewUri: "data:image/jpeg;base64,aGVsbG8=",
142 }),
143 ]);
144 expect(files.get(uri)?.deleted).toBe(false);
145 });
146​
147 it("renders unsupported images to JPEG and removes the cache file after attaching", async () => {
148 const uri = "content://media/external/images/media/43";
149 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
150 manipulator.state.sourceSize = { width: 100, height: 100 };
151​
152 const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
153​
154 expect(attachments).toEqual([
155 expect.objectContaining({
156 name: "pasted-image.jpeg",
157 mimeType: "image/jpeg",
158 dataUrl: "data:image/jpeg;base64,cmVuZGVyZWQ=",
159 previewUri: "data:image/jpeg;base64,cmVuZGVyZWQ=",
160 }),
161 ]);
162 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
163 expect(files.get(uri)?.deleted).toBe(false);
164 });
165​
166 it("removes the rendered JPEG when its bytes exceed the image limit", async () => {
167 const uri = "content://media/external/images/media/43";
168 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
169 manipulator.state.sourceSize = { width: 100, height: 100 };
170 manipulator.state.renderedBase64 = "A".repeat(
171 Math.ceil((PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1) / 3) * 4,
172 );
173​
174 const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
175​
176 expect(attachments).toEqual([]);
177 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
178 expect(files.get(uri)?.deleted).toBe(false);
179 });
180​
181 it("converts owned files to data-backed previews and deletes the source", async () => {
182 const uri =
183 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
184 files.set(uri, { base64: "aGVsbG8=", deleted: false });
185​
186 const attachments = await convertPastedImagesToAttachments({
187 uris: [uri],
188 existingCount: 0,
189 });
190​
191 expect(attachments).toEqual([
192 expect.objectContaining({
193 dataUrl: "data:image/png;base64,aGVsbG8=",
194 previewUri: "data:image/png;base64,aGVsbG8=",
195 }),
196 ]);
197 expect(files.get(uri)?.deleted).toBe(true);
198 });
199​
200 it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
201 const rejected =
202 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
203 const overflow =
204 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
205 const userOwned = "file:///private/var/mobile/photos/library.png";
206 files.set(rejected, { base64: "", deleted: false });
207 files.set(overflow, { base64: "aGVsbG8=", deleted: false });
208 files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
209​
210 await convertPastedImagesToAttachments({
211 uris: [rejected, overflow, userOwned],
212 existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
213 });
214​
215 expect(files.get(rejected)?.deleted).toBe(true);
216 expect(files.get(overflow)?.deleted).toBe(true);
217 expect(files.get(userOwned)?.deleted).toBe(false);
218 });
219});
220​
221describe("persistComposerAttachmentFile", () => {
222 beforeEach(() => {
223 files.clear();
224 });
225​
226 it("stores picked files under a name Android's java.net.URI accepts", async () => {
227 const source = "file:///cache/DocumentPicker/Report [draft].pdf";
228 files.set(source, { base64: "JVBERg==", deleted: false });
229​
230 const fileUri = await persistComposerAttachmentFile(source, "Report [draft].pdf");
231​
232 // expo-file-system encodes spaces and `%` but leaves `[`, `]`, `|` and `^` raw.
233 expect(fileUri.split("/").at(-1)).toMatch(/^[\w\-.!~*'();:@&=+$, %]+\.pdf$/);
234 });
235});
236​
237describe("composerStripAttachments", () => {
238 const image = {
239 id: "img-1",
240 type: "image" as const,
241 name: "shot.jpg",
242 mimeType: "image/jpeg",
243 sizeBytes: 10,
244 dataUrl: "",
245 };
246 const video = {
247 id: "vid-1",
248 type: "file" as const,
249 name: "clip.mp4",
250 mimeType: "video/mp4",
251 sizeBytes: 20,
252 fileUri: "file:///clip.mp4",
253 };
254 const doc = {
255 id: "doc-1",
256 type: "file" as const,
257 name: "notes.txt",
258 mimeType: "text/plain",
259 sizeBytes: 5,
260 fileUri: "file:///notes.txt",
261 };
262​
263 it("keeps media beside a document rather than dropping the whole strip", async () => {
264 const { composerStripAttachments } = await import("./composerImages");
265 expect(composerStripAttachments([doc, image, video] as never).map((a) => a.id)).toEqual([
266 "img-1",
267 "vid-1",
268 ]);
269 });
270​
271 it("keeps oversized document-picked images visible while sending them as files", async () => {
272 const { composerStripAttachments, isComposerImageAttachment } =
273 await import("./composerImages");
274 const oversizedImage = {
275 ...video,
276 id: "large-image",
277 name: "large.png",
278 mimeType: "image/png",
279 fileUri: "file:///large.png",
280 sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
281 };
282​
283 expect(composerStripAttachments([oversizedImage])).toEqual([oversizedImage]);
284 expect(isComposerImageAttachment(oversizedImage)).toBe(false);
285 });
286});