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

composerImages.ts

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