Open History to see the last commit
1import { SymbolView } from "../components/AppSymbol";
2import { videoMimeType } from "@t3tools/shared/video";
3import { useEffect, useMemo, useState } from "react";
4import { Image, Pressable, ScrollView, View } from "react-native";
5
6import { AppText as Text } from "./AppText";
7import { PierreEntryIcon } from "./PierreEntryIcon";
8import {
9 isFileBackedComposerAttachment,
10 type DraftComposerAttachment,
11 type DraftComposerFileAttachment,
12 type DraftComposerImageAttachment,
13} from "../lib/composerImages";
14import { resolveOwnedComposerAttachmentFileUri } from "../lib/composerAttachmentFiles";
15import { VideoAttachmentTile } from "./VideoAttachmentTile";
16import type { MediaActionsSource } from "../lib/mediaActions";
17import { PresentationSource } from "./NativePresentation";
18import type { FilePreviewSource } from "./FilePreviewModal";
19import { isPdfFile } from "../lib/filePreview";
20import type { EnvironmentId } from "@t3tools/contracts";
21import {
22 retryComposerAttachmentUpload,
23 useComposerAttachmentUploadState,
24} from "../state/composer-attachment-uploads";
25
26export interface ComposerAttachmentStripProps {
27 readonly environmentId?: EnvironmentId;
28 /** Attachments to display. */
29 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
30 /** Called when the user removes an attachment. */
31 readonly onRemove: (imageId: string) => void;
32 /** Called when the user taps an image or PDF to preview it. */
33 readonly onPressPreview?: (source: FilePreviewSource) => void;
34 readonly onPressVideo?: (
35 attachment: DraftComposerFileAttachment,
36 sourceIdentifier: string,
37 ) => void;
38 /** Image thumbnail size in points. Defaults to 72. */
39 readonly imageSize?: number;
40 /** Border radius of each image thumbnail. Defaults to 16. */
41 readonly imageBorderRadius?: number;
42 /** Whether the remove button should sit in its own gutter instead of overlapping the image. */
43 readonly removeButtonPlacement?: "overlay" | "gutter";
44}
45
46type ComposerAttachmentThumbnailProps = {
47 readonly environmentId?: EnvironmentId;
48 readonly attachment: DraftComposerAttachment;
49 readonly size: number;
50 readonly borderRadius: number;
51 readonly compact?: boolean;
52 readonly onPressPreview?: (source: FilePreviewSource) => void;
53 readonly onPressVideo?: (
54 attachment: DraftComposerFileAttachment,
55 sourceIdentifier: string,
56 ) => void;
57};
58
59export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailProps) {
60 const upload = useComposerAttachmentUploadState(props.environmentId, props.attachment.id);
61 return (
62 <View style={{ width: props.size, height: props.size }}>
63 <ComposerAttachmentContent {...props} />
64 {upload && upload.status !== "ready" ? (
65 <Pressable
66 accessibilityRole={upload.status === "failed" ? "button" : "text"}
67 accessibilityLabel={
68 upload.status === "failed"
69 ? `Retry uploading ${props.attachment.name}`
70 : `Uploading ${props.attachment.name}, ${Math.floor(upload.progress * 100)}%`
71 }
72 accessibilityHint={upload.status === "failed" ? upload.reason : undefined}
73 disabled={upload.status !== "failed"}
74 onPress={() =>
75 props.environmentId &&
76 retryComposerAttachmentUpload(props.environmentId, props.attachment.id)
77 }
78 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"
79 >
80 <SymbolView
81 name={upload.status === "failed" ? "arrow.clockwise" : "arrow.up"}
82 size={props.compact ? 8 : 10}
83 tintColor="#ffffff"
84 type="monochrome"
85 />
86 {!props.compact ? (
87 <Text className="text-2xs text-white">
88 {upload.status === "failed" ? "Retry" : `${Math.floor(upload.progress * 100)}%`}
89 </Text>
90 ) : null}
91 </Pressable>
92 ) : null}
93 </View>
94 );
95}
96
97/**
98 * Thumbnail URI for a draft image. File-backed previews rebase into the
99 * current iOS data container (its UUID changes across installs); the raw
100 * persisted URI renders meanwhile, which is correct everywhere but after a
101 * container move.
102 */
103function useComposerImagePreviewUri(attachment: DraftComposerImageAttachment): string {
104 const { fileUri, previewUri } = attachment;
105 const [rebased, setRebased] = useState<{ fileUri: string; uri: string } | null>(null);
106 useEffect(() => {
107 if (fileUri === undefined) return;
108 let cancelled = false;
109 void (async () => {
110 const { Paths } = await import("expo-file-system");
111 const owned = resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri);
112 // Re-render only when the container actually moved.
113 if (!cancelled && owned !== null && owned !== previewUri) setRebased({ fileUri, uri: owned });
114 })();
115 return () => {
116 cancelled = true;
117 };
118 }, [fileUri, previewUri]);
119 return fileUri !== undefined && rebased?.fileUri === fileUri ? rebased.uri : previewUri;
120}
121
122function ComposerImageAttachment(
123 props: ComposerAttachmentThumbnailProps & { readonly attachment: DraftComposerImageAttachment },
124) {
125 const { attachment } = props;
126 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
127 const previewUri = useComposerImagePreviewUri(attachment);
128 const sourceIdentifier = `draft-image:${attachment.id}`;
129 return (
130 <PresentationSource identifier={sourceIdentifier}>
131 <Pressable
132 accessibilityRole="imagebutton"
133 accessibilityLabel={`Open ${attachment.name}`}
134 disabled={!props.onPressPreview}
135 onPress={() =>
136 props.onPressPreview?.(
137 // File-backed images open through the retain-lease + container
138 // rebase path; legacy drafts still carry their inline bytes.
139 isFileBackedComposerAttachment(attachment)
140 ? { kind: "image", attachment, name: attachment.name, sourceIdentifier }
141 : {
142 kind: "image",
143 uri: attachment.dataUrl ?? attachment.previewUri,
144 name: attachment.name,
145 sourceIdentifier,
146 },
147 )
148 }
149 >
150 <Image
151 source={{ uri: previewUri }}
152 style={style}
153 className="bg-subtle"
154 resizeMode="cover"
155 />
156 </Pressable>
157 </PresentationSource>
158 );
159}
160
161function ComposerAttachmentContent(props: ComposerAttachmentThumbnailProps) {
162 const { attachment } = props;
163 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
164 if (attachment.type === "image") {
165 return <ComposerImageAttachment {...props} attachment={attachment} />;
166 }
167 const onPressVideo = props.onPressVideo;
168 if (onPressVideo && videoMimeType(attachment) !== null) {
169 return (
170 <ComposerVideoAttachment {...props} attachment={attachment} onPressVideo={onPressVideo} />
171 );
172 }
173 const canPreview = isPdfFile(attachment) && props.onPressPreview !== undefined;
174 const sourceIdentifier = `draft-file:${attachment.id}`;
175 return (
176 <PresentationSource identifier={sourceIdentifier}>
177 <Pressable
178 accessibilityRole="button"
179 accessibilityLabel={`Open ${attachment.name}`}
180 disabled={!canPreview}
181 onPress={() =>
182 props.onPressPreview?.({
183 kind: "pdf",
184 name: attachment.name,
185 attachment,
186 sourceIdentifier,
187 })
188 }
189 className={
190 props.compact
191 ? "items-center justify-center bg-subtle"
192 : "items-center justify-center gap-1 bg-subtle px-2"
193 }
194 style={style}
195 >
196 <PierreEntryIcon path={attachment.name} kind="file" size={props.compact ? 15 : 22} />
197 {!props.compact ? (
198 <Text className="w-full text-center text-2xs text-foreground" numberOfLines={1}>
199 {attachment.name}
200 </Text>
201 ) : null}
202 </Pressable>
203 </PresentationSource>
204 );
205}
206
207function ComposerVideoAttachment(props: {
208 readonly attachment: DraftComposerFileAttachment;
209 readonly size: number;
210 readonly borderRadius: number;
211 readonly compact?: boolean;
212 readonly onPressVideo: (
213 attachment: DraftComposerFileAttachment,
214 sourceIdentifier: string,
215 ) => void;
216}) {
217 const { attachment } = props;
218 const sourceIdentifier = `draft:${attachment.id}`;
219 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
220 const actionsSource = useMemo<MediaActionsSource>(
221 () => ({
222 name: attachment.name,
223 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
224 sourceIdentifier,
225 attachment,
226 }),
227 [attachment, sourceIdentifier],
228 );
229
230 return (
231 <VideoAttachmentTile
232 name={attachment.name}
233 sourceIdentifier={sourceIdentifier}
234 thumbnailSource={attachment}
235 compact={props.compact}
236 onPress={() => props.onPressVideo(attachment, sourceIdentifier)}
237 actionsSource={actionsSource}
238 style={style}
239 />
240 );
241}
242
243/**
244 * Attachment thumbnails used by the thread composer and the new-task draft screen.
245 */
246export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
247 const size = props.imageSize ?? 72;
248 const radius = props.imageBorderRadius ?? 16;
249 const removeButtonPlacement = props.removeButtonPlacement ?? "overlay";
250 const removeButtonGutter = removeButtonPlacement === "gutter" ? 10 : 0;
251
252 if (props.attachments.length === 0) {
253 return null;
254 }
255
256 return (
257 <ScrollView
258 horizontal
259 showsHorizontalScrollIndicator={false}
260 keyboardShouldPersistTaps="always"
261 className="grow-0"
262 >
263 <View className="flex-row gap-2.5">
264 {props.attachments.map((attachment) => (
265 <View
266 key={attachment.id}
267 className="relative"
268 style={{
269 paddingTop: removeButtonGutter,
270 paddingRight: removeButtonGutter,
271 }}
272 >
273 <ComposerAttachmentThumbnail
274 environmentId={props.environmentId}
275 attachment={attachment}
276 size={size}
277 borderRadius={radius}
278 onPressPreview={props.onPressPreview}
279 onPressVideo={props.onPressVideo}
280 />
281 <Pressable
282 className="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"
283 style={{
284 top: removeButtonPlacement === "gutter" ? 0 : 4,
285 right: removeButtonPlacement === "gutter" ? 0 : 4,
286 }}
287 hitSlop={6}
288 onPress={() => props.onRemove(attachment.id)}
289 >
290 <SymbolView
291 name="xmark"
292 size={9}
293 tintColor="#ffffff"
294 type="monochrome"
295 weight="bold"
296 />
297 </Pressable>
298 </View>
299 ))}
300 </View>
301 </ScrollView>
302 );
303}