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