Open History to see the last commit
1import {
2 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
3 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
4 type UploadChatImageAttachment,
5} from "@t3tools/contracts";
6import { uuidv4 } from "./uuid";
7
8export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
9 readonly id: string;
10 readonly previewUri: string;
11}
12
13const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
14
15function estimateBase64ByteSize(base64: string): number {
16 const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
17 return Math.floor((base64.length * 3) / 4) - padding;
18}
19
20async function loadImagePicker() {
21 try {
22 return await import("expo-image-picker");
23 } catch (error) {
24 throw new Error("Image attachments are unavailable right now.", { cause: error });
25 }
26}
27
28async function loadClipboard() {
29 try {
30 return await import("expo-clipboard");
31 } catch (error) {
32 throw new Error("Clipboard paste is unavailable right now.", { cause: error });
33 }
34}
35
36export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
37 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
38 readonly error: string | null;
39}> {
40 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
41 if (remainingSlots <= 0) {
42 return {
43 images: [],
44 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
45 };
46 }
47
48 let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>;
49 try {
50 imagePicker = await loadImagePicker();
51 } catch (error) {
52 return {
53 images: [],
54 error:
55 error instanceof Error ? error.message : "Image attachments are unavailable right now.",
56 };
57 }
58
59 const permission = await imagePicker.requestMediaLibraryPermissionsAsync();
60 if (!permission.granted) {
61 return {
62 images: [],
63 error: "Allow photo library access to attach images.",
64 };
65 }
66
67 const result = await imagePicker.launchImageLibraryAsync({
68 mediaTypes: ["images"],
69 allowsMultipleSelection: true,
70 selectionLimit: remainingSlots,
71 base64: true,
72 quality: 1,
73 });
74
75 if (result.canceled) {
76 return {
77 images: [],
78 error: null,
79 };
80 }
81
82 const nextImages: DraftComposerImageAttachment[] = [];
83 let error: string | null = null;
84
85 for (const asset of result.assets) {
86 const mimeType = asset.mimeType?.toLowerCase();
87 if (!mimeType?.startsWith("image/")) {
88 error = `Unsupported file type for '${asset.fileName ?? "image"}'.`;
89 continue;
90 }
91
92 const base64 = asset.base64;
93 if (!base64) {
94 error = `Failed to read '${asset.fileName ?? "image"}'.`;
95 continue;
96 }
97
98 const sizeBytes = asset.fileSize ?? estimateBase64ByteSize(base64);
99 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
100 error = `'${asset.fileName ?? "image"}' exceeds the 10 MB attachment limit.`;
101 continue;
102 }
103
104 nextImages.push({
105 id: uuidv4(),
106 type: "image",
107 name: asset.fileName ?? "image",
108 mimeType,
109 sizeBytes,
110 dataUrl: `data:${mimeType};base64,${base64}`,
111 previewUri: asset.uri,
112 });
113 }
114
115 return {
116 images: nextImages,
117 error,
118 };
119}
120
121export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<{
122 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
123 readonly text: string | null;
124 readonly error: string | null;
125}> {
126 let clipboard: Awaited<ReturnType<typeof loadClipboard>>;
127 try {
128 clipboard = await loadClipboard();
129 } catch (error) {
130 return {
131 images: [],
132 text: null,
133 error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
134 };
135 }
136
137 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
138
139 if (await clipboard.hasImageAsync()) {
140 if (remainingSlots <= 0) {
141 return {
142 images: [],
143 text: null,
144 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
145 };
146 }
147 const image = await clipboard.getImageAsync({ format: "png" });
148 if (!image) {
149 return {
150 images: [],
151 text: null,
152 error: "Clipboard image is unavailable.",
153 };
154 }
155
156 const base64 = image.data.split(",")[1] ?? "";
157 const sizeBytes = estimateBase64ByteSize(base64);
158 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
159 return {
160 images: [],
161 text: null,
162 error: "Clipboard image exceeds the 10 MB attachment limit.",
163 };
164 }
165
166 return {
167 images: [
168 {
169 id: uuidv4(),
170 type: "image",
171 name: "pasted-image.png",
172 mimeType: "image/png",
173 sizeBytes,
174 dataUrl: image.data,
175 previewUri: image.data,
176 },
177 ],
178 text: null,
179 error: null,
180 };
181 }
182
183 if (await clipboard.hasStringAsync()) {
184 const text = await clipboard.getStringAsync();
185 return {
186 images: [],
187 text: text.length > 0 ? text : null,
188 error: text.length > 0 ? null : "Clipboard is empty.",
189 };
190 }
191
192 return {
193 images: [],
194 text: null,
195 error: "Clipboard does not contain pasteable text or image content.",
196 };
197}
198
199function mimeTypeFromUri(uri: string): string {
200 const ext = uri.split(".").pop()?.toLowerCase();
201 switch (ext) {
202 case "png":
203 return "image/png";
204 case "jpg":
205 case "jpeg":
206 return "image/jpeg";
207 case "gif":
208 return "image/gif";
209 case "webp":
210 return "image/webp";
211 case "heic":
212 return "image/heic";
213 default:
214 return "image/png";
215 }
216}
217
218export function isOwnedPastedImageUri(uri: string): boolean {
219 try {
220 const url = new URL(uri);
221 if (url.protocol !== "file:") {
222 return false;
223 }
224 const segments = url.pathname.split("/").filter(Boolean);
225 return (
226 segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY && segments.at(-1)?.endsWith(".png") === true
227 );
228 } catch {
229 return false;
230 }
231}
232
233export async function convertPastedImagesToAttachments(input: {
234 readonly uris: ReadonlyArray<string>;
235 readonly existingCount: number;
236}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
237 const { File } = await import("expo-file-system");
238 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
239 const results: DraftComposerImageAttachment[] = [];
240
241 for (const [index, uri] of input.uris.entries()) {
242 const ownedTemporaryFile = isOwnedPastedImageUri(uri);
243 try {
244 if (index >= Math.max(0, remainingSlots)) {
245 continue;
246 }
247 const file = new File(uri);
248 const base64 = await file.base64();
249 const sizeBytes = estimateBase64ByteSize(base64);
250 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
251 continue;
252 }
253 const mimeType = mimeTypeFromUri(uri);
254 results.push({
255 id: uuidv4(),
256 type: "image",
257 name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
258 mimeType,
259 sizeBytes,
260 dataUrl: `data:${mimeType};base64,${base64}`,
261 previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
262 });
263 } catch (error) {
264 console.warn("Failed to read pasted image", uri, error);
265 } finally {
266 if (ownedTemporaryFile) {
267 try {
268 const file = new File(uri);
269 if (file.exists) {
270 file.delete();
271 }
272 } catch (error) {
273 console.warn("Failed to remove temporary pasted image", uri, error);
274 }
275 }
276 }
277 }
278
279 return results;
280}