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/** Fabric re-parses URLs each layout; large data URLs can stall and abort commits. */
99const INLINE_PREVIEW_FALLBACK_MAX_CHARS = 256_000;
100
101async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<string | null> {
102 const comma = dataUrl.indexOf(",");
103 if (comma < 0) return null;
104 const { Directory, File, Paths } = await import("expo-file-system");
105 const mimeType = /^data:([^;,]+)/.exec(dataUrl)?.[1] ?? "image/jpeg";
106 const extension = (mimeType.split("/")[1] ?? "jpg").replace("jpeg", "jpg");
107 const directory = new Directory(Paths.cache, PREVIEW_CACHE_DIRECTORY);
108 directory.create({ idempotent: true, intermediates: true });
109 const file = new File(directory, `${id}.${extension}`);
110 if (!file.exists) {
111 file.create();
112 await file.write(dataUrl.slice(comma + 1), { encoding: "base64" });
113 }
114 return file.uri;
115}
116
117function useComposerImagePreviewUri(attachment: DraftComposerImageAttachment): string | null {
118 const { id, fileUri, previewUri } = attachment;
119 const [rebased, setRebased] = useState<{ fileUri: string; uri: string } | null>(null);
120 const [materialized, setMaterialized] = useState<{ id: string; uri: string | null } | null>(null);
121 const inlinePreview = fileUri === undefined && previewUri.startsWith("data:");
122 useEffect(() => {
123 if (fileUri === undefined) return;
124 let cancelled = false;
125 void (async () => {
126 const { Paths } = await import("expo-file-system");
127 const owned = resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri);
128 if (!cancelled && owned !== null && owned !== previewUri) setRebased({ fileUri, uri: owned });
129 })();
130 return () => {
131 cancelled = true;
132 };
133 }, [fileUri, previewUri]);
134 useEffect(() => {
135 if (!inlinePreview) return;
136 let cancelled = false;
137 void materializeDataUrlPreview(id, previewUri)
138 .then((uri) => {
139 if (!cancelled && uri !== null) setMaterialized({ id, uri });
140 })
141 .catch((error: unknown) => {
142 console.warn("[composer-attachments] could not cache an image preview", error);
143 if (!cancelled) setMaterialized({ id, uri: null });
144 });
145 return () => {
146 cancelled = true;
147 };
148 }, [id, inlinePreview, previewUri]);
149 if (fileUri !== undefined && rebased?.fileUri === fileUri) return rebased.uri;
150 if (fileUri !== undefined) return previewUri.startsWith("data:") ? fileUri : previewUri;
151 if (inlinePreview) {
152 if (materialized?.id !== id) return null;
153 return (
154 materialized.uri ??
155 (previewUri.length <= INLINE_PREVIEW_FALLBACK_MAX_CHARS ? previewUri : null)
156 );
157 }
158 return previewUri;
159}
160
161function ComposerImageAttachment(
162 props: ComposerAttachmentThumbnailProps & { readonly attachment: DraftComposerImageAttachment },
163) {
164 const { attachment } = props;
165 const withGallery = useFilePreviewGallery();
166 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
167 const previewUri = useComposerImagePreviewUri(attachment);
168 const sourceIdentifier = `draft-image:${attachment.id}`;
169 return (
170 <PresentationSource identifier={sourceIdentifier}>
171 <Pressable
172 accessibilityRole="imagebutton"
173 accessibilityLabel={`Open ${attachment.name}`}
174 disabled={!props.onPressPreview}
175 onPress={() =>
176 props.onPressPreview?.(
177 withGallery(
178 isFileBackedComposerAttachment(attachment)
179 ? { kind: "image", attachment, name: attachment.name, sourceIdentifier }
180 : {
181 kind: "image",
182 uri: attachment.dataUrl ?? attachment.previewUri,
183 name: attachment.name,
184 sourceIdentifier,
185 },
186 ),
187 )
188 }
189 >
190 <Image
191 source={previewUri === null ? undefined : { uri: previewUri }}
192 style={style}
193 className="bg-subtle"
194 resizeMode="cover"
195 />
196 </Pressable>
197 </PresentationSource>
198 );
199}
200
201function ComposerAttachmentContent(props: ComposerAttachmentThumbnailProps) {
202 const { attachment } = props;
203 // The document picker types every pick as a plain file, so a picture arrives here as one.
204 if (attachment.type === "image" || imageMimeType(attachment) !== null) {
205 const { source: _droppedSource, ...rest } = attachment;
206 return (
207 <ComposerImageAttachment
208 {...props}
209 attachment={
210 attachment.type === "image"
211 ? attachment
212 : { ...rest, type: "image", previewUri: attachment.fileUri }
213 }
214 />
215 );
216 }
217 const onPressVideo = props.onPressVideo;
218 if (onPressVideo && videoMimeType(attachment) !== null) {
219 return (
220 <ComposerVideoAttachment {...props} attachment={attachment} onPressVideo={onPressVideo} />
221 );
222 }
223 return <ComposerFileAttachment {...props} attachment={attachment} />;
224}
225
226function ComposerFileAttachment(
227 props: ComposerAttachmentThumbnailProps & { readonly attachment: DraftComposerFileAttachment },
228) {
229 const { attachment } = props;
230 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
231 const canPreview = isPdfFile(attachment) && props.onPressPreview !== undefined;
232 const sourceIdentifier = `draft-file:${attachment.id}`;
233 const onPressDocument = props.onPressDocument;
234 return (
235 <>
236 <PresentationSource identifier={sourceIdentifier}>
237 <Pressable
238 accessibilityRole="button"
239 accessibilityLabel={`Open ${attachment.name}`}
240 disabled={!canPreview && onPressDocument === undefined}
241 onPress={() =>
242 canPreview
243 ? props.onPressPreview?.({
244 kind: "pdf",
245 name: attachment.name,
246 attachment,
247 sourceIdentifier,
248 })
249 : onPressDocument?.(attachment)
250 }
251 className={
252 props.compact
253 ? "items-center justify-center bg-subtle"
254 : "items-center justify-center gap-1 bg-subtle px-2"
255 }
256 style={style}
257 >
258 <PierreEntryIcon path={attachment.name} kind="file" size={props.compact ? 15 : 22} />
259 {!props.compact ? (
260 <Text className="w-full text-center text-2xs text-foreground" numberOfLines={1}>
261 {attachment.name}
262 </Text>
263 ) : null}
264 </Pressable>
265 </PresentationSource>
266 </>
267 );
268}
269
270function ComposerVideoAttachment(props: {
271 readonly attachment: DraftComposerFileAttachment;
272 readonly size: number;
273 readonly borderRadius: number;
274 readonly compact?: boolean;
275 readonly onPressVideo: (
276 attachment: DraftComposerFileAttachment,
277 sourceIdentifier: string,
278 ) => void;
279}) {
280 const { attachment } = props;
281 const sourceIdentifier = `draft:${attachment.id}`;
282 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
283 const actionsSource = useMemo<MediaActionsSource>(
284 () => ({
285 name: attachment.name,
286 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
287 sourceIdentifier,
288 attachment,
289 }),
290 [attachment, sourceIdentifier],
291 );
292
293 return (
294 <VideoAttachmentTile
295 name={attachment.name}
296 sourceIdentifier={sourceIdentifier}
297 thumbnailSource={attachment}
298 compact={props.compact}
299 onPress={() => props.onPressVideo(attachment, sourceIdentifier)}
300 actionsSource={actionsSource}
301 style={style}
302 />
303 );
304}
305
306export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
307 const gallery = useMemo(() => composerImageGallery(props.attachments), [props.attachments]);
308 const size = props.imageSize ?? 72;
309 const radius = props.imageBorderRadius ?? 16;
310 const removeButtonPlacement = props.removeButtonPlacement ?? "overlay";
311 const removeButtonGutter = removeButtonPlacement === "gutter" ? 10 : 0;
312
313 if (props.attachments.length === 0) {
314 return null;
315 }
316
317 return (
318 <FilePreviewGallery value={gallery}>
319 <ScrollView
320 horizontal
321 showsHorizontalScrollIndicator={false}
322 keyboardShouldPersistTaps="always"
323 className="grow-0"
324 >
325 <View className="flex-row gap-2.5">
326 {props.attachments.map((attachment) => (
327 <View
328 key={attachment.id}
329 className="relative"
330 style={{
331 paddingTop: removeButtonGutter,
332 paddingRight: removeButtonGutter,
333 }}
334 >
335 <ComposerAttachmentThumbnail
336 environmentId={props.environmentId}
337 attachment={attachment}
338 size={size}
339 borderRadius={radius}
340 onPressPreview={props.onPressPreview}
341 onPressVideo={props.onPressVideo}
342 onPressDocument={props.onPressDocument}
343 />
344 <Pressable
345 accessibilityRole="button"
346 accessibilityLabel={`Remove ${attachment.name}`}
347 className="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"
348 style={{
349 top: removeButtonPlacement === "gutter" ? 0 : 4,
350 right: removeButtonPlacement === "gutter" ? 0 : 4,
351 }}
352 hitSlop={6}
353 onPress={() => props.onRemove(attachment.id)}
354 >
355 <SymbolView
356 name="xmark"
357 size={9}
358 tintColor="#ffffff"
359 type="monochrome"
360 weight="bold"
361 />
362 </Pressable>
363 </View>
364 ))}
365 </View>
366 </ScrollView>
367 </FilePreviewGallery>
368 );
369}