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

composerImages.test.ts

256 lines8.2 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 async base64(): Promise<string> {
63 const entry = files.get(this.uri);
64 if (!entry || entry.deleted) {
65 throw new Error("missing file");
66 }
67 return entry.base64;
68 }
69​
70 delete(): void {
71 const entry = files.get(this.uri);
72 if (entry) {
73 entry.deleted = true;
74 }
75 }
76​
77 create(): void {
78 files.set(this.uri, { base64: "", deleted: false });
79 }
80​
81 write(text: string): void {
82 files.set(this.uri, { base64: "", deleted: false, text });
83 }
84​
85 moveSync(destination: { readonly uri: string }): void {
86 const entry = files.get(this.uri);
87 if (!entry) throw new Error("missing staged file");
88 files.set(destination.uri, entry);
89 files.delete(this.uri);
90 }
91 },
92 Directory: class {
93 readonly uri: string;
94​
95 constructor(parent: string, name: string) {
96 this.uri = `${parent}/${name}`;
97 }
98​
99 create(): void {}
100 },
101 Paths: { document: "file:///documents" },
102}));
103​
104vi.mock("./uuid", () => ({
105 uuidv4: () => "attachment-id",
106}));
107​
108import { convertPastedImagesToAttachments } from "./composerImages";
109​
110describe("native pasted image cleanup", () => {
111 beforeEach(() => {
112 files.clear();
113 manipulator.state.renderedBase64 = "cmVuZGVyZWQ=";
114 });
115​
116 it("preserves the reported image type of extensionless Android content URIs", async () => {
117 const uri = "content://media/external/images/media/42";
118 files.set(uri, { base64: "aGVsbG8=", deleted: false, mimeType: "image/jpeg" });
119​
120 const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
121​
122 expect(attachments).toEqual([
123 expect.objectContaining({
124 name: "pasted-image.jpeg",
125 mimeType: "image/jpeg",
126 dataUrl: "data:image/jpeg;base64,aGVsbG8=",
127 previewUri: "data:image/jpeg;base64,aGVsbG8=",
128 }),
129 ]);
130 expect(files.get(uri)?.deleted).toBe(false);
131 });
132​
133 it("renders unsupported images to JPEG and removes the cache file after attaching", async () => {
134 const uri = "content://media/external/images/media/43";
135 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
136 manipulator.state.sourceSize = { width: 100, height: 100 };
137​
138 const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
139​
140 expect(attachments).toEqual([
141 expect.objectContaining({
142 name: "pasted-image.jpeg",
143 mimeType: "image/jpeg",
144 dataUrl: "data:image/jpeg;base64,cmVuZGVyZWQ=",
145 previewUri: "data:image/jpeg;base64,cmVuZGVyZWQ=",
146 }),
147 ]);
148 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
149 expect(files.get(uri)?.deleted).toBe(false);
150 });
151​
152 it("removes the rendered JPEG when its bytes exceed the image limit", async () => {
153 const uri = "content://media/external/images/media/43";
154 files.set(uri, { base64: "b3JpZ2luYWw=", deleted: false, mimeType: "image/heic" });
155 manipulator.state.sourceSize = { width: 100, height: 100 };
156 manipulator.state.renderedBase64 = "A".repeat(
157 Math.ceil((PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1) / 3) * 4,
158 );
159​
160 const attachments = await convertPastedImagesToAttachments({ uris: [uri], existingCount: 0 });
161​
162 expect(attachments).toEqual([]);
163 expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true);
164 expect(files.get(uri)?.deleted).toBe(false);
165 });
166​
167 it("converts owned files to data-backed previews and deletes the source", async () => {
168 const uri =
169 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
170 files.set(uri, { base64: "aGVsbG8=", deleted: false });
171​
172 const attachments = await convertPastedImagesToAttachments({
173 uris: [uri],
174 existingCount: 0,
175 });
176​
177 expect(attachments).toEqual([
178 expect.objectContaining({
179 dataUrl: "data:image/png;base64,aGVsbG8=",
180 previewUri: "data:image/png;base64,aGVsbG8=",
181 }),
182 ]);
183 expect(files.get(uri)?.deleted).toBe(true);
184 });
185​
186 it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
187 const rejected =
188 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
189 const overflow =
190 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
191 const userOwned = "file:///private/var/mobile/photos/library.png";
192 files.set(rejected, { base64: "", deleted: false });
193 files.set(overflow, { base64: "aGVsbG8=", deleted: false });
194 files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
195​
196 await convertPastedImagesToAttachments({
197 uris: [rejected, overflow, userOwned],
198 existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
199 });
200​
201 expect(files.get(rejected)?.deleted).toBe(true);
202 expect(files.get(overflow)?.deleted).toBe(true);
203 expect(files.get(userOwned)?.deleted).toBe(false);
204 });
205});
206​
207describe("composerStripAttachments", () => {
208 const image = {
209 id: "img-1",
210 type: "image" as const,
211 name: "shot.jpg",
212 mimeType: "image/jpeg",
213 sizeBytes: 10,
214 dataUrl: "",
215 };
216 const video = {
217 id: "vid-1",
218 type: "file" as const,
219 name: "clip.mp4",
220 mimeType: "video/mp4",
221 sizeBytes: 20,
222 fileUri: "file:///clip.mp4",
223 };
224 const doc = {
225 id: "doc-1",
226 type: "file" as const,
227 name: "notes.txt",
228 mimeType: "text/plain",
229 sizeBytes: 5,
230 fileUri: "file:///notes.txt",
231 };
232​
233 it("keeps media beside a document rather than dropping the whole strip", async () => {
234 const { composerStripAttachments } = await import("./composerImages");
235 expect(composerStripAttachments([doc, image, video] as never).map((a) => a.id)).toEqual([
236 "img-1",
237 "vid-1",
238 ]);
239 });
240​
241 it("keeps oversized document-picked images visible while sending them as files", async () => {
242 const { composerStripAttachments, isComposerImageAttachment } =
243 await import("./composerImages");
244 const oversizedImage = {
245 ...video,
246 id: "large-image",
247 name: "large.png",
248 mimeType: "image/png",
249 fileUri: "file:///large.png",
250 sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
251 };
252​
253 expect(composerStripAttachments([oversizedImage])).toEqual([oversizedImage]);
254 expect(isComposerImageAttachment(oversizedImage)).toBe(false);
255 });
256});