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

composerImages.ts

281 lines7.5 KB

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;
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 }));
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 }
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 }
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 result = await imagePicker.launchImageLibraryAsync({
69 mediaTypes: ["images"],
70 allowsMultipleSelection: true,
71 selectionLimit: remainingSlots,
72 base64: true,
73 quality: 1,
74 });
75​
76 if (result.canceled) {
77 return {
78 images: [],
79 error: null,
80 };
81 }
82​
83 const nextImages: DraftComposerImageAttachment[] = [];
84 let error: string | null = null;
85​
86 for (const asset of result.assets) {
87 const mimeType = asset.mimeType?.toLowerCase();
88 if (!mimeType?.startsWith("image/")) {
89 error = `Unsupported file type for '${asset.fileName ?? "image"}'.`;
90 continue;
91 }
92​
93 const base64 = asset.base64;
94 if (!base64) {
95 error = `Failed to read '${asset.fileName ?? "image"}'.`;
96 continue;
97 }
98​
99 const sizeBytes = asset.fileSize ?? estimateBase64ByteSize(base64);
100 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
101 error = `'${asset.fileName ?? "image"}' exceeds the 10 MB attachment limit.`;
102 continue;
103 }
104​
105 nextImages.push({
106 id: uuidv4(),
107 type: "image",
108 name: asset.fileName ?? "image",
109 mimeType,
110 sizeBytes,
111 dataUrl: `data:${mimeType};base64,${base64}`,
112 previewUri: asset.uri,
113 });
114 }
115​
116 return {
117 images: nextImages,
118 error,
119 };
121​
122export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<{
123 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
124 readonly text: string | null;
125 readonly error: string | null;
126}> {
127 let clipboard: Awaited<ReturnType<typeof loadClipboard>>;
128 try {
129 clipboard = await loadClipboard();
130 } catch (error) {
131 return {
132 images: [],
133 text: null,
134 error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
135 };
136 }
137​
138 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
139​
140 if (await clipboard.hasImageAsync()) {
141 if (remainingSlots <= 0) {
142 return {
143 images: [],
144 text: null,
145 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
146 };
147 }
148 const image = await clipboard.getImageAsync({ format: "png" });
149 if (!image) {
150 return {
151 images: [],
152 text: null,
153 error: "Clipboard image is unavailable.",
154 };
155 }
156​
157 const base64 = image.data.split(",")[1] ?? "";
158 const sizeBytes = estimateBase64ByteSize(base64);
159 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
160 return {
161 images: [],
162 text: null,
163 error: "Clipboard image exceeds the 10 MB attachment limit.",
164 };
165 }
166​
167 return {
168 images: [
169 {
170 id: uuidv4(),
171 type: "image",
172 name: "pasted-image.png",
173 mimeType: "image/png",
174 sizeBytes,
175 dataUrl: image.data,
176 previewUri: image.data,
177 },
178 ],
179 text: null,
180 error: null,
181 };
182 }
183​
184 if (await clipboard.hasStringAsync()) {
185 const text = await clipboard.getStringAsync();
186 return {
187 images: [],
188 text: text.length > 0 ? text : null,
189 error: text.length > 0 ? null : "Clipboard is empty.",
190 };
191 }
192​
193 return {
194 images: [],
195 text: null,
196 error: "Clipboard does not contain pasteable text or image content.",
197 };
199​
200function mimeTypeFromUri(uri: string): string {
201 const ext = uri.split(".").pop()?.toLowerCase();
202 switch (ext) {
203 case "png":
204 return "image/png";
205 case "jpg":
206 case "jpeg":
207 return "image/jpeg";
208 case "gif":
209 return "image/gif";
210 case "webp":
211 return "image/webp";
212 case "heic":
213 return "image/heic";
214 default:
215 return "image/png";
216 }
218​
219export function isOwnedPastedImageUri(uri: string): boolean {
220 try {
221 const url = new URL(uri);
222 if (url.protocol !== "file:") {
223 return false;
224 }
225 const segments = url.pathname.split("/").filter(Boolean);
226 return (
227 segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY && segments.at(-1)?.endsWith(".png") === true
228 );
229 } catch {
230 return false;
231 }
233​
234export async function convertPastedImagesToAttachments(input: {
235 readonly uris: ReadonlyArray<string>;
236 readonly existingCount: number;
237}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
238 const { File } = await import("expo-file-system");
239 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
240 const results: DraftComposerImageAttachment[] = [];
241​
242 for (const [index, uri] of input.uris.entries()) {
243 const ownedTemporaryFile = isOwnedPastedImageUri(uri);
244 try {
245 if (index >= Math.max(0, remainingSlots)) {
246 continue;
247 }
248 const file = new File(uri);
249 const base64 = await file.base64();
250 const sizeBytes = estimateBase64ByteSize(base64);
251 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
252 continue;
253 }
254 const mimeType = mimeTypeFromUri(uri);
255 results.push({
256 id: uuidv4(),
257 type: "image",
258 name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
259 mimeType,
260 sizeBytes,
261 dataUrl: `data:${mimeType};base64,${base64}`,
262 previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
263 });
264 } catch (error) {
265 console.warn("Failed to read pasted image", uri, error);
266 } finally {
267 if (ownedTemporaryFile) {
268 try {
269 const file = new File(uri);
270 if (file.exists) {
271 file.delete();
272 }
273 } catch (error) {
274 console.warn("Failed to remove temporary pasted image", uri, error);
275 }
276 }
277 }
278 }
279​
280 return results;