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

composerImages.test.ts

266 lines8.0 KB

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