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

composerImages.test.ts

285 lines8.6 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<string, { base64: string; deleted: boolean; text?: string }>();
8​
9const clipboard = vi.hoisted(() => ({
10 hasImageAsync: vi.fn(),
11 getImageAsync: vi.fn(),
12 hasStringAsync: vi.fn(),
13 getStringAsync: vi.fn(),
14}));
15​
16vi.mock("expo-clipboard", () => clipboard);
17​
18const manipulator = vi.hoisted(() => {
19 const state = { sourceSize: { width: 0, height: 0 } };
20 const manipulate = vi.fn((source: string | { width: number; height: number }) => {
21 let size = typeof source === "string" ? state.sourceSize : source;
22 const context = {
23 resize: vi.fn((next: { width: number; height: number }) => {
24 size = next;
25 return context;
26 }),
27 renderAsync: vi.fn(async () => ({
28 ...size,
29 release: vi.fn(),
30 saveAsync: vi.fn(async (options: { format: string }) => ({
31 uri: `file:///cache/rendered.${options.format}`,
32 base64: `cmVuZGVyZWQ=`,
33 })),
34 })),
35 };
36 return context;
37 });
38 return { state, manipulate };
39});
40​
41vi.mock("expo-image-manipulator", () => ({
42 ImageManipulator: { manipulate: manipulator.manipulate },
43 SaveFormat: { JPEG: "jpeg", PNG: "png" },
44}));
45​
46vi.mock("expo-file-system", () => ({
47 File: class {
48 readonly uri: string;
49 readonly name: string;
50 readonly parentDirectory: { readonly uri: string };
51​
52 constructor(parent: string | { readonly uri: string }, name?: string) {
53 const parentUri = typeof parent === "string" ? parent : parent.uri;
54 this.uri = name ? `${parentUri}/${name}` : parentUri;
55 this.name = name ?? this.uri.split("/").at(-1) ?? "file";
56 this.parentDirectory = { uri: this.uri.slice(0, -(this.name.length + 1)) };
57 }
58​
59 get exists(): boolean {
60 return files.has(this.uri) && files.get(this.uri)?.deleted === false;
61 }
62​
63 async base64(): Promise<string> {
64 const entry = files.get(this.uri);
65 if (!entry || entry.deleted) {
66 throw new Error("missing file");
67 }
68 return entry.base64;
69 }
70​
71 delete(): void {
72 const entry = files.get(this.uri);
73 if (entry) {
74 entry.deleted = true;
75 }
76 }
77​
78 create(): void {
79 files.set(this.uri, { base64: "", deleted: false });
80 }
81​
82 write(text: string): void {
83 files.set(this.uri, { base64: "", deleted: false, text });
84 }
85​
86 moveSync(destination: { readonly uri: string }): void {
87 const entry = files.get(this.uri);
88 if (!entry) throw new Error("missing staged file");
89 files.set(destination.uri, entry);
90 files.delete(this.uri);
91 }
92 },
93 Directory: class {
94 readonly uri: string;
95​
96 constructor(parent: string, name: string) {
97 this.uri = `${parent}/${name}`;
98 }
99​
100 create(): void {}
101 },
102 Paths: { document: "file:///documents" },
103}));
104​
105vi.mock("./uuid", () => ({
106 uuidv4: () => "attachment-id",
107}));
108​
109import { convertPastedImagesToAttachments, pasteComposerClipboard } from "./composerImages";
110​
111describe("composer clipboard paste", () => {
112 beforeEach(() => {
113 vi.clearAllMocks();
114 clipboard.hasImageAsync.mockResolvedValue(false);
115 clipboard.hasStringAsync.mockResolvedValue(true);
116 clipboard.getStringAsync.mockResolvedValue("clipboard text");
117 clipboard.getImageAsync.mockResolvedValue({ data: "data:image/png;base64,aGVsbG8=" });
118 });
119​
120 it("returns only the image when the clipboard contains both image and text", async () => {
121 clipboard.hasImageAsync.mockResolvedValue(true);
122 const result = await pasteComposerClipboard({ existingCount: 0 });
123 expect(result).toEqual({
124 images: [expect.objectContaining({ type: "image", name: "pasted-image.png" })],
125 text: null,
126 error: null,
127 });
128 expect(clipboard.getStringAsync).not.toHaveBeenCalled();
129 });
130​
131 it("does not paste alternate text when the image cannot fit", async () => {
132 clipboard.hasImageAsync.mockResolvedValue(true);
133 expect(
134 await pasteComposerClipboard({ existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS }),
135 ).toEqual({ images: [], text: null, error: expect.stringContaining("up to") });
136 expect(clipboard.getStringAsync).not.toHaveBeenCalled();
137 });
138});
139​
140describe("oversized pasted images", () => {
141 const u32 = (n: number) => [(n >>> 24) & 0xff, (n >>> 16) & 0xff, (n >>> 8) & 0xff, n & 0xff];
142 const pngDataUrl = (width: number, height: number) =>
143 `data:image/png;base64,${Buffer.from([
144 0x89,
145 0x50,
146 0x4e,
147 0x47,
148 0x0d,
149 0x0a,
150 0x1a,
151 0x0a,
152 ...u32(13),
153 0x49,
154 0x48,
155 0x44,
156 0x52,
157 ...u32(width),
158 ...u32(height),
159 8,
160 6,
161 0,
162 0,
163 0,
164 ]).toString("base64")}`;
165​
166 beforeEach(() => {
167 vi.clearAllMocks();
168 clipboard.hasImageAsync.mockResolvedValue(true);
169 });
170​
171 it("scales a clipboard screenshot over 2000px to 2000px and keeps it a PNG", async () => {
172 manipulator.state.sourceSize = { width: 3024, height: 1964 };
173 const pasted = pngDataUrl(3024, 1964);
174 clipboard.getImageAsync.mockResolvedValue({ data: pasted });
175​
176 const result = await pasteComposerClipboard({ existingCount: 0 });
177​
178 expect(manipulator.manipulate).toHaveBeenCalledWith(pasted);
179 const resize = manipulator.manipulate.mock.results.at(-1)?.value.resize;
180 expect(resize).toHaveBeenCalledWith({ width: 2000, height: 1299 });
181 expect(result.images).toEqual([
182 expect.objectContaining({
183 mimeType: "image/png",
184 dataUrl: "data:image/png;base64,cmVuZGVyZWQ=",
185 previewUri: "data:image/png;base64,cmVuZGVyZWQ=",
186 }),
187 ]);
188 });
189});
190​
191describe("native pasted image cleanup", () => {
192 beforeEach(() => {
193 files.clear();
194 });
195​
196 it("converts owned files to data-backed previews and deletes the source", async () => {
197 const uri =
198 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png";
199 files.set(uri, { base64: "aGVsbG8=", deleted: false });
200​
201 const attachments = await convertPastedImagesToAttachments({
202 uris: [uri],
203 existingCount: 0,
204 });
205​
206 expect(attachments).toEqual([
207 expect.objectContaining({
208 dataUrl: "data:image/png;base64,aGVsbG8=",
209 previewUri: "data:image/png;base64,aGVsbG8=",
210 }),
211 ]);
212 expect(files.get(uri)?.deleted).toBe(true);
213 });
214​
215 it("deletes rejected and overflow owned files without deleting user-owned files", async () => {
216 const rejected =
217 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/bad.png";
218 const overflow =
219 "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/overflow.png";
220 const userOwned = "file:///private/var/mobile/photos/library.png";
221 files.set(rejected, { base64: "", deleted: false });
222 files.set(overflow, { base64: "aGVsbG8=", deleted: false });
223 files.set(userOwned, { base64: "aGVsbG8=", deleted: false });
224​
225 await convertPastedImagesToAttachments({
226 uris: [rejected, overflow, userOwned],
227 existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1,
228 });
229​
230 expect(files.get(rejected)?.deleted).toBe(true);
231 expect(files.get(overflow)?.deleted).toBe(true);
232 expect(files.get(userOwned)?.deleted).toBe(false);
233 });
234});
235​
236describe("composerStripAttachments", () => {
237 const image = {
238 id: "img-1",
239 type: "image" as const,
240 name: "shot.jpg",
241 mimeType: "image/jpeg",
242 sizeBytes: 10,
243 dataUrl: "",
244 };
245 const video = {
246 id: "vid-1",
247 type: "file" as const,
248 name: "clip.mp4",
249 mimeType: "video/mp4",
250 sizeBytes: 20,
251 fileUri: "file:///clip.mp4",
252 };
253 const doc = {
254 id: "doc-1",
255 type: "file" as const,
256 name: "notes.txt",
257 mimeType: "text/plain",
258 sizeBytes: 5,
259 fileUri: "file:///notes.txt",
260 };
261​
262 it("keeps media beside a document rather than dropping the whole strip", async () => {
263 const { composerStripAttachments } = await import("./composerImages");
264 expect(composerStripAttachments([doc, image, video] as never).map((a) => a.id)).toEqual([
265 "img-1",
266 "vid-1",
267 ]);
268 });
269​
270 it("keeps oversized document-picked images visible while sending them as files", async () => {
271 const { composerStripAttachments, isComposerImageAttachment } =
272 await import("./composerImages");
273 const oversizedImage = {
274 ...video,
275 id: "large-image",
276 name: "large.png",
277 mimeType: "image/png",
278 fileUri: "file:///large.png",
279 sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1,
280 };
281​
282 expect(composerStripAttachments([oversizedImage])).toEqual([oversizedImage]);
283 expect(isComposerImageAttachment(oversizedImage)).toBe(false);
284 });
285});