Open History to see the last commit
1import { SymbolView } from "../components/AppSymbol";
2import { imageMimeType } from "@t3tools/shared/image";
3import { videoMimeType } from "@t3tools/shared/video";
4import { useEffect, useMemo, useState } from "react";
5import { Image, Pressable, ScrollView, View } from "react-native";
6
7import { AppText as Text } from "./AppText";
8import { PierreEntryIcon } from "./PierreEntryIcon";
9import {
10 isFileBackedComposerAttachment,
11 type DraftComposerAttachment,
12 type DraftComposerFileAttachment,
13 type DraftComposerImageAttachment,
14} from "../lib/composerImages";
15import { resolveOwnedComposerAttachmentFileUri } from "../lib/composerAttachmentFiles";
16import { VideoAttachmentTile } from "./VideoAttachmentTile";
17import { type MediaActionsSource } from "../lib/mediaActions";
18import { PresentationSource } from "./NativePresentation";
19import type { FilePreviewSource } from "./FilePreviewModal";
20import { isPdfFile } from "../lib/filePreview";
21import type { EnvironmentId } from "@t3tools/contracts";
22import {
23 retryComposerAttachmentUpload,
24 useComposerAttachmentUploadState,
25} from "../state/composer-attachment-uploads";
26
27export interface ComposerAttachmentStripProps {
28 readonly environmentId?: EnvironmentId;
29 /** Attachments to display. */
30 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
31 /** Called when the user removes an attachment. */
32 readonly onRemove: (imageId: string) => void;
33 /** Called when the user taps an image or PDF to preview it. */
34 readonly onPressPreview?: (source: FilePreviewSource) => void;
35 readonly onPressVideo?: (
36 attachment: DraftComposerFileAttachment,
37 sourceIdentifier: string,
38 ) => void;
39 /** Called when the user taps a document that is not a picture, video or PDF. */
40 readonly onPressDocument?: (attachment: DraftComposerFileAttachment) => void;
41 /** Image thumbnail size in points. Defaults to 72. */
42 readonly imageSize?: number;
43 /** Border radius of each image thumbnail. Defaults to 16. */
44 readonly imageBorderRadius?: number;
45 /** Whether the remove button should sit in its own gutter instead of overlapping the image. */
46 readonly removeButtonPlacement?: "overlay" | "gutter";
47}
48
49type ComposerAttachmentThumbnailProps = {
50 readonly environmentId?: EnvironmentId;
51 readonly attachment: DraftComposerAttachment;
52 readonly size: number;
53 readonly borderRadius: number;
54 readonly compact?: boolean;
55 readonly onPressPreview?: (source: FilePreviewSource) => void;
56 readonly onPressVideo?: (
57 attachment: DraftComposerFileAttachment,
58 sourceIdentifier: string,
59 ) => void;
60 readonly onPressDocument?: (attachment: DraftComposerFileAttachment) => void;
61};
62
63export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailProps) {
64 const upload = useComposerAttachmentUploadState(props.environmentId, props.attachment.id);
65 return (
66 <View style={{ width: props.size, height: props.size }}>
67 <ComposerAttachmentContent {...props} />
68 {upload && upload.status !== "ready" ? (
69 <Pressable
70 accessibilityRole={upload.status === "failed" ? "button" : "text"}
71 accessibilityLabel={
72 upload.status === "failed"
73 ? `Retry uploading ${props.attachment.name}`
74 : `Uploading ${props.attachment.name}, ${Math.floor(upload.progress * 100)}%`
75 }
76 accessibilityHint={upload.status === "failed" ? upload.reason : undefined}
77 disabled={upload.status !== "failed"}
78 onPress={() =>
79 props.environmentId &&
80 retryComposerAttachmentUpload(props.environmentId, props.attachment.id)
81 }
82 className="absolute bottom-0.5 left-0.5 flex-row items-center gap-0.5 rounded-full bg-black/70 px-1 py-0.5"
83 >
84 <SymbolView
85 name={upload.status === "failed" ? "arrow.clockwise" : "arrow.up"}
86 size={props.compact ? 8 : 10}
87 tintColor="#ffffff"
88 type="monochrome"
89 />
90 {!props.compact ? (
91 <Text className="text-2xs text-white">
92 {upload.status === "failed" ? "Retry" : `${Math.floor(upload.progress * 100)}%`}
93 </Text>
94 ) : null}
95 </Pressable>
96 ) : null}
97 </View>
98 );
99}
100
101/**
102 * Thumbnail URI for a draft image. File-backed previews rebase into the
103 * current iOS data container (its UUID changes across installs); the raw
104 * persisted URI renders meanwhile, which is correct everywhere but after a
105 * container move.
106 */
107const PREVIEW_CACHE_DIRECTORY = "t3-composer-previews";
108
109/**
110 * Fabric re-parses an image source URL on every layout pass of the node, and a
111 * multi-megabyte data URL makes each Fabric commit slow enough that concurrent
112 * UI-thread commits (the question card's coverage animation) win the race every
113 * time until the renderer aborts. Inline bytes are written to the cache once and
114 * the thumbnail renders from that file instead.
115 */
116/** Roughly 192KB of base64: small enough that re-parsing it per layout stays imperceptible. */
117const INLINE_PREVIEW_FALLBACK_MAX_CHARS = 256_000;
118
119async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<string | null> {
120 const comma = dataUrl.indexOf(",");
121 if (comma < 0) return null;
122 const { Directory, File, Paths } = await import("expo-file-system");
123 const mimeType = /^data:([^;,]+)/.exec(dataUrl)?.[1] ?? "image/jpeg";
124 const extension = (mimeType.split("/")[1] ?? "jpg").replace("jpeg", "jpg");
125 const directory = new Directory(Paths.cache, PREVIEW_CACHE_DIRECTORY);
126 directory.create({ idempotent: true, intermediates: true });
127 const file = new File(directory, `${id}.${extension}`);
128 if (!file.exists) {
129 file.create();
130 await file.write(dataUrl.slice(comma + 1), { encoding: "base64" });
131 }
132 return file.uri;
133}
134
135/** The thumbnail source for a draft image: an owned file when there is one, never a data URL. */
136function useComposerImagePreviewUri(attachment: DraftComposerImageAttachment): string | null {
137 const { id, fileUri, previewUri } = attachment;
138 const [rebased, setRebased] = useState<{ fileUri: string; uri: string } | null>(null);
139 const [materialized, setMaterialized] = useState<{ id: string; uri: string | null } | null>(null);
140 const inlinePreview = fileUri === undefined && previewUri.startsWith("data:");
141 useEffect(() => {
142 if (fileUri === undefined) return;
143 let cancelled = false;
144 void (async () => {
145 const { Paths } = await import("expo-file-system");
146 const owned = resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri);
147 // Re-render only when the container actually moved.
148 if (!cancelled && owned !== null && owned !== previewUri) setRebased({ fileUri, uri: owned });
149 })();
150 return () => {
151 cancelled = true;
152 };
153 }, [fileUri, previewUri]);
154 useEffect(() => {
155 if (!inlinePreview) return;
156 let cancelled = false;
157 void materializeDataUrlPreview(id, previewUri)
158 .then((uri) => {
159 if (!cancelled && uri !== null) setMaterialized({ id, uri });
160 })
161 .catch((error: unknown) => {
162 console.warn("[composer-attachments] could not cache an image preview", error);
163 // Record the failure so the thumbnail stops waiting on a file that will never arrive.
164 if (!cancelled) setMaterialized({ id, uri: null });
165 });
166 return () => {
167 cancelled = true;
168 };
169 }, [id, inlinePreview, previewUri]);
170 if (fileUri !== undefined && rebased?.fileUri === fileUri) return rebased.uri;
171 if (fileUri !== undefined) return previewUri.startsWith("data:") ? fileUri : previewUri;
172 if (inlinePreview) {
173 if (materialized?.id !== id) return null;
174 // Falling back to the data URL is a last resort: a large one re-parses on every layout and
175 // starves the Fabric commit, which is what the cache file exists to avoid. Small ones are
176 // cheap enough to render directly rather than leaving the thumbnail blank forever.
177 return (
178 materialized.uri ??
179 (previewUri.length <= INLINE_PREVIEW_FALLBACK_MAX_CHARS ? previewUri : null)
180 );
181 }
182 return previewUri;
183}
184
185function ComposerImageAttachment(
186 props: ComposerAttachmentThumbnailProps & { readonly attachment: DraftComposerImageAttachment },
187) {
188 const { attachment } = props;
189 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
190 const previewUri = useComposerImagePreviewUri(attachment);
191 const sourceIdentifier = `draft-image:${attachment.id}`;
192 return (
193 <PresentationSource identifier={sourceIdentifier}>
194 <Pressable
195 accessibilityRole="imagebutton"
196 accessibilityLabel={`Open ${attachment.name}`}
197 disabled={!props.onPressPreview}
198 onPress={() =>
199 props.onPressPreview?.(
200 // File-backed images open through the retain-lease + container
201 // rebase path; legacy drafts still carry their inline bytes.
202 isFileBackedComposerAttachment(attachment)
203 ? { kind: "image", attachment, name: attachment.name, sourceIdentifier }
204 : {
205 kind: "image",
206 uri: attachment.dataUrl ?? attachment.previewUri,
207 name: attachment.name,
208 sourceIdentifier,
209 },
210 )
211 }
212 >
213 <Image
214 source={previewUri === null ? undefined : { uri: previewUri }}
215 style={style}
216 className="bg-subtle"
217 resizeMode="cover"
218 />
219 </Pressable>
220 </PresentationSource>
221 );
222}
223
224function ComposerAttachmentContent(props: ComposerAttachmentThumbnailProps) {
225 const { attachment } = props;
226 // The document picker types every pick as a plain file, so a picture arrives here as one.
227 // What it *is* decides how it presents, the same way videos are already recognised below.
228 if (attachment.type === "image" || imageMimeType(attachment) !== null) {
229 // A pasted-text marker does not fit the snapshot source a picture carries.
230 const { source: _droppedSource, ...rest } = attachment;
231 return (
232 <ComposerImageAttachment
233 {...props}
234 attachment={
235 attachment.type === "image"
236 ? attachment
237 : { ...rest, type: "image", previewUri: attachment.fileUri }
238 }
239 />
240 );
241 }
242 const onPressVideo = props.onPressVideo;
243 if (onPressVideo && videoMimeType(attachment) !== null) {
244 return (
245 <ComposerVideoAttachment {...props} attachment={attachment} onPressVideo={onPressVideo} />
246 );
247 }
248 return <ComposerFileAttachment {...props} attachment={attachment} />;
249}
250
251function ComposerFileAttachment(
252 props: ComposerAttachmentThumbnailProps & { readonly attachment: DraftComposerFileAttachment },
253) {
254 const { attachment } = props;
255 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
256 const canPreview = isPdfFile(attachment) && props.onPressPreview !== undefined;
257 const sourceIdentifier = `draft-file:${attachment.id}`;
258 const onPressDocument = props.onPressDocument;
259 return (
260 <>
261 <PresentationSource identifier={sourceIdentifier}>
262 <Pressable
263 accessibilityRole="button"
264 accessibilityLabel={`Open ${attachment.name}`}
265 disabled={!canPreview && onPressDocument === undefined}
266 onPress={() =>
267 canPreview
268 ? props.onPressPreview?.({
269 kind: "pdf",
270 name: attachment.name,
271 attachment,
272 sourceIdentifier,
273 })
274 : onPressDocument?.(attachment)
275 }
276 className={
277 props.compact
278 ? "items-center justify-center bg-subtle"
279 : "items-center justify-center gap-1 bg-subtle px-2"
280 }
281 style={style}
282 >
283 <PierreEntryIcon path={attachment.name} kind="file" size={props.compact ? 15 : 22} />
284 {!props.compact ? (
285 <Text className="w-full text-center text-2xs text-foreground" numberOfLines={1}>
286 {attachment.name}
287 </Text>
288 ) : null}
289 </Pressable>
290 </PresentationSource>
291 </>
292 );
293}
294
295function ComposerVideoAttachment(props: {
296 readonly attachment: DraftComposerFileAttachment;
297 readonly size: number;
298 readonly borderRadius: number;
299 readonly compact?: boolean;
300 readonly onPressVideo: (
301 attachment: DraftComposerFileAttachment,
302 sourceIdentifier: string,
303 ) => void;
304}) {
305 const { attachment } = props;
306 const sourceIdentifier = `draft:${attachment.id}`;
307 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
308 const actionsSource = useMemo<MediaActionsSource>(
309 () => ({
310 name: attachment.name,
311 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
312 sourceIdentifier,
313 attachment,
314 }),
315 [attachment, sourceIdentifier],
316 );
317
318 return (
319 <VideoAttachmentTile
320 name={attachment.name}
321 sourceIdentifier={sourceIdentifier}
322 thumbnailSource={attachment}
323 compact={props.compact}
324 onPress={() => props.onPressVideo(attachment, sourceIdentifier)}
325 actionsSource={actionsSource}
326 style={style}
327 />
328 );
329}
330
331/**
332 * Attachment thumbnails used by the thread composer and the new-task draft screen.
333 */
334export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
335 const size = props.imageSize ?? 72;
336 const radius = props.imageBorderRadius ?? 16;
337 const removeButtonPlacement = props.removeButtonPlacement ?? "overlay";
338 const removeButtonGutter = removeButtonPlacement === "gutter" ? 10 : 0;
339
340 if (props.attachments.length === 0) {
341 return null;
342 }
343
344 return (
345 <ScrollView
346 horizontal
347 showsHorizontalScrollIndicator={false}
348 keyboardShouldPersistTaps="always"
349 className="grow-0"
350 >
351 <View className="flex-row gap-2.5">
352 {props.attachments.map((attachment) => (
353 <View
354 key={attachment.id}
355 className="relative"
356 style={{
357 paddingTop: removeButtonGutter,
358 paddingRight: removeButtonGutter,
359 }}
360 >
361 <ComposerAttachmentThumbnail
362 environmentId={props.environmentId}
363 attachment={attachment}
364 size={size}
365 borderRadius={radius}
366 onPressPreview={props.onPressPreview}
367 onPressVideo={props.onPressVideo}
368 onPressDocument={props.onPressDocument}
369 />
370 <Pressable
371 className="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"
372 style={{
373 top: removeButtonPlacement === "gutter" ? 0 : 4,
374 right: removeButtonPlacement === "gutter" ? 0 : 4,
375 }}
376 hitSlop={6}
377 onPress={() => props.onRemove(attachment.id)}
378 >
379 <SymbolView
380 name="xmark"
381 size={9}
382 tintColor="#ffffff"
383 type="monochrome"
384 weight="bold"
385 />
386 </Pressable>
387 </View>
388 ))}
389 </View>
390 </ScrollView>
391 );
392}