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

ComposerAttachmentStrip.tsx

377 lines13.9 KB

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