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