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