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