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

ComposerAttachmentStrip.tsx

390 lines14.7 KB

1import { SymbolView } from "../components/AppSymbol";
2import { imageMimeType } from "@t3tools/shared/image";
3import { videoMimeType } from "@t3tools/shared/video";
4import { useEffect, useMemo, useState } from "react";
5import { Image, Pressable, ScrollView, View } from "react-native";
6​
7import { AppText as Text } from "./AppText";
8import { PierreEntryIcon } from "./PierreEntryIcon";
9import {
10 isFileBackedComposerAttachment,
11 type DraftComposerAttachment,
12 type DraftComposerFileAttachment,
13 type DraftComposerImageAttachment,
14} from "../lib/composerImages";
15import { resolveOwnedComposerAttachmentFileUri } from "../lib/composerAttachmentFiles";
16import { VideoAttachmentTile } from "./VideoAttachmentTile";
17import { type MediaActionsSource } from "../lib/mediaActions";
18import { PresentationSource } from "./NativePresentation";
19import type { FilePreviewSource } from "./FilePreviewModal";
20import { isPdfFile } from "../lib/filePreview";
21import type { EnvironmentId } from "@t3tools/contracts";
22import {
23 retryComposerAttachmentUpload,
24 useComposerAttachmentUploadState,
25} from "../state/composer-attachment-uploads";
26​
27export interface ComposerAttachmentStripProps {
28 readonly environmentId?: EnvironmentId;
29 /** Attachments to display. */
30 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
31 /** Called when the user removes an attachment. */
32 readonly onRemove: (imageId: string) => void;
33 /** Called when the user taps an image or PDF to preview it. */
34 readonly onPressPreview?: (source: FilePreviewSource) => void;
35 readonly onPressVideo?: (
36 attachment: DraftComposerFileAttachment,
37 sourceIdentifier: string,
38 ) => void;
39 /** Called when the user taps a document that is not a picture, video or PDF. */
40 readonly onPressDocument?: (attachment: DraftComposerFileAttachment) => void;
41 /** Image thumbnail size in points. Defaults to 72. */
42 readonly imageSize?: number;
43 /** Border radius of each image thumbnail. Defaults to 16. */
44 readonly imageBorderRadius?: number;
45 /** Whether the remove button should sit in its own gutter instead of overlapping the image. */
46 readonly removeButtonPlacement?: "overlay" | "gutter";
48​
49type ComposerAttachmentThumbnailProps = {
50 readonly environmentId?: EnvironmentId;
51 readonly attachment: DraftComposerAttachment;
52 readonly size: number;
53 readonly borderRadius: number;
54 readonly compact?: boolean;
55 readonly onPressPreview?: (source: FilePreviewSource) => void;
56 readonly onPressVideo?: (
57 attachment: DraftComposerFileAttachment,
58 sourceIdentifier: string,
59 ) => void;
60 readonly onPressDocument?: (attachment: DraftComposerFileAttachment) => void;
61};
62​
63export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailProps) {
64 const upload = useComposerAttachmentUploadState(props.environmentId, props.attachment.id);
65 return (
66 <View style={{ width: props.size, height: props.size }}>
67 <ComposerAttachmentContent {...props} />
68 {upload && upload.status !== "ready" ? (
69 <Pressable
70 accessibilityRole={upload.status === "failed" ? "button" : "text"}
71 accessibilityLabel={
72 upload.status === "failed"
73 ? `Retry uploading ${props.attachment.name}`
74 : `Uploading ${props.attachment.name}, ${Math.floor(upload.progress * 100)}%`
75 }
76 accessibilityHint={upload.status === "failed" ? upload.reason : undefined}
77 disabled={upload.status !== "failed"}
78 onPress={() =>
79 props.environmentId &&
80 retryComposerAttachmentUpload(props.environmentId, props.attachment.id)
81 }
82 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"
83 >
84 <SymbolView
85 name={upload.status === "failed" ? "arrow.clockwise" : "arrow.up"}
86 size={props.compact ? 8 : 10}
87 tintColor="#ffffff"
88 type="monochrome"
89 />
90 {!props.compact ? (
91 <Text className="text-2xs text-white">
92 {upload.status === "failed" ? "Retry" : `${Math.floor(upload.progress * 100)}%`}
93 </Text>
94 ) : null}
95 </Pressable>
96 ) : null}
97 </View>
98 );
100​
101/**
102 * Thumbnail URI for a draft image. File-backed previews rebase into the
103 * current iOS data container (its UUID changes across installs); the raw
104 * persisted URI renders meanwhile, which is correct everywhere but after a
105 * container move.
106 */
107const PREVIEW_CACHE_DIRECTORY = "t3-composer-previews";
108​
109/**
110 * Fabric re-parses an image source URL on every layout pass of the node, and a
111 * multi-megabyte data URL makes each Fabric commit slow enough that concurrent
112 * UI-thread commits (the question card's coverage animation) win the race every
113 * time until the renderer aborts. Inline bytes are written to the cache once and
114 * the thumbnail renders from that file instead.
115 */
116/** Roughly 192KB of base64: small enough that re-parsing it per layout stays imperceptible. */
117const INLINE_PREVIEW_FALLBACK_MAX_CHARS = 256_000;
118​
119async function materializeDataUrlPreview(id: string, dataUrl: string): Promise<string | null> {
120 const comma = dataUrl.indexOf(",");
121 if (comma < 0) return null;
122 const { Directory, File, Paths } = await import("expo-file-system");
123 const mimeType = /^data:([^;,]+)/.exec(dataUrl)?.[1] ?? "image/jpeg";
124 const extension = (mimeType.split("/")[1] ?? "jpg").replace("jpeg", "jpg");
125 const directory = new Directory(Paths.cache, PREVIEW_CACHE_DIRECTORY);
126 directory.create({ idempotent: true, intermediates: true });
127 const file = new File(directory, `${id}.${extension}`);
128 if (!file.exists) {
129 file.create();
130 file.write(dataUrl.slice(comma + 1), { encoding: "base64" });
131 }
132 return file.uri;
134​
135/** The thumbnail source for a draft image: an owned file when there is one, never a data URL. */
136function useComposerImagePreviewUri(attachment: DraftComposerImageAttachment): string | null {
137 const { id, fileUri, previewUri } = attachment;
138 const [rebased, setRebased] = useState<{ fileUri: string; uri: string } | null>(null);
139 const [materialized, setMaterialized] = useState<{ id: string; uri: string | null } | null>(null);
140 const inlinePreview = fileUri === undefined && previewUri.startsWith("data:");
141 useEffect(() => {
142 if (fileUri === undefined) return;
143 let cancelled = false;
144 void (async () => {
145 const { Paths } = await import("expo-file-system");
146 const owned = resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri);
147 // Re-render only when the container actually moved.
148 if (!cancelled && owned !== null && owned !== previewUri) setRebased({ fileUri, uri: owned });
149 })();
150 return () => {
151 cancelled = true;
152 };
153 }, [fileUri, previewUri]);
154 useEffect(() => {
155 if (!inlinePreview) return;
156 let cancelled = false;
157 void materializeDataUrlPreview(id, previewUri)
158 .then((uri) => {
159 if (!cancelled && uri !== null) setMaterialized({ id, uri });
160 })
161 .catch((error: unknown) => {
162 console.warn("[composer-attachments] could not cache an image preview", error);
163 // Record the failure so the thumbnail stops waiting on a file that will never arrive.
164 if (!cancelled) setMaterialized({ id, uri: null });
165 });
166 return () => {
167 cancelled = true;
168 };
169 }, [id, inlinePreview, previewUri]);
170 if (fileUri !== undefined && rebased?.fileUri === fileUri) return rebased.uri;
171 if (fileUri !== undefined) return previewUri.startsWith("data:") ? fileUri : previewUri;
172 if (inlinePreview) {
173 if (materialized?.id !== id) return null;
174 // Falling back to the data URL is a last resort: a large one re-parses on every layout and
175 // starves the Fabric commit, which is what the cache file exists to avoid. Small ones are
176 // cheap enough to render directly rather than leaving the thumbnail blank forever.
177 return (
178 materialized.uri ??
179 (previewUri.length <= INLINE_PREVIEW_FALLBACK_MAX_CHARS ? previewUri : null)
180 );
181 }
182 return previewUri;
184​
185function ComposerImageAttachment(
186 props: ComposerAttachmentThumbnailProps & { readonly attachment: DraftComposerImageAttachment },
187) {
188 const { attachment } = props;
189 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
190 const previewUri = useComposerImagePreviewUri(attachment);
191 const sourceIdentifier = `draft-image:${attachment.id}`;
192 return (
193 <PresentationSource identifier={sourceIdentifier}>
194 <Pressable
195 accessibilityRole="imagebutton"
196 accessibilityLabel={`Open ${attachment.name}`}
197 disabled={!props.onPressPreview}
198 onPress={() =>
199 props.onPressPreview?.(
200 // File-backed images open through the retain-lease + container
201 // rebase path; legacy drafts still carry their inline bytes.
202 isFileBackedComposerAttachment(attachment)
203 ? { kind: "image", attachment, name: attachment.name, sourceIdentifier }
204 : {
205 kind: "image",
206 uri: attachment.dataUrl ?? attachment.previewUri,
207 name: attachment.name,
208 sourceIdentifier,
209 },
210 )
211 }
212 >
213 <Image
214 source={previewUri === null ? undefined : { uri: previewUri }}
215 style={style}
216 className="bg-subtle"
217 resizeMode="cover"
218 />
219 </Pressable>
220 </PresentationSource>
221 );
223​
224function ComposerAttachmentContent(props: ComposerAttachmentThumbnailProps) {
225 const { attachment } = props;
226 // The document picker types every pick as a plain file, so a picture arrives here as one.
227 // What it *is* decides how it presents, the same way videos are already recognised below.
228 if (attachment.type === "image" || imageMimeType(attachment) !== null) {
229 return (
230 <ComposerImageAttachment
231 {...props}
232 attachment={
233 attachment.type === "image"
234 ? attachment
235 : { ...attachment, type: "image", previewUri: attachment.fileUri }
236 }
237 />
238 );
239 }
240 const onPressVideo = props.onPressVideo;
241 if (onPressVideo && videoMimeType(attachment) !== null) {
242 return (
243 <ComposerVideoAttachment {...props} attachment={attachment} onPressVideo={onPressVideo} />
244 );
245 }
246 return <ComposerFileAttachment {...props} attachment={attachment} />;
248​
249function ComposerFileAttachment(
250 props: ComposerAttachmentThumbnailProps & { readonly attachment: DraftComposerFileAttachment },
251) {
252 const { attachment } = props;
253 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
254 const canPreview = isPdfFile(attachment) && props.onPressPreview !== undefined;
255 const sourceIdentifier = `draft-file:${attachment.id}`;
256 const onPressDocument = props.onPressDocument;
257 return (
258 <>
259 <PresentationSource identifier={sourceIdentifier}>
260 <Pressable
261 accessibilityRole="button"
262 accessibilityLabel={`Open ${attachment.name}`}
263 disabled={!canPreview && onPressDocument === undefined}
264 onPress={() =>
265 canPreview
266 ? props.onPressPreview?.({
267 kind: "pdf",
268 name: attachment.name,
269 attachment,
270 sourceIdentifier,
271 })
272 : onPressDocument?.(attachment)
273 }
274 className={
275 props.compact
276 ? "items-center justify-center bg-subtle"
277 : "items-center justify-center gap-1 bg-subtle px-2"
278 }
279 style={style}
280 >
281 <PierreEntryIcon path={attachment.name} kind="file" size={props.compact ? 15 : 22} />
282 {!props.compact ? (
283 <Text className="w-full text-center text-2xs text-foreground" numberOfLines={1}>
284 {attachment.name}
285 </Text>
286 ) : null}
287 </Pressable>
288 </PresentationSource>
289 </>
290 );
292​
293function ComposerVideoAttachment(props: {
294 readonly attachment: DraftComposerFileAttachment;
295 readonly size: number;
296 readonly borderRadius: number;
297 readonly compact?: boolean;
298 readonly onPressVideo: (
299 attachment: DraftComposerFileAttachment,
300 sourceIdentifier: string,
301 ) => void;
302}) {
303 const { attachment } = props;
304 const sourceIdentifier = `draft:${attachment.id}`;
305 const style = { width: props.size, height: props.size, borderRadius: props.borderRadius };
306 const actionsSource = useMemo<MediaActionsSource>(
307 () => ({
308 name: attachment.name,
309 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
310 sourceIdentifier,
311 attachment,
312 }),
313 [attachment, sourceIdentifier],
314 );
315​
316 return (
317 <VideoAttachmentTile
318 name={attachment.name}
319 sourceIdentifier={sourceIdentifier}
320 thumbnailSource={attachment}
321 compact={props.compact}
322 onPress={() => props.onPressVideo(attachment, sourceIdentifier)}
323 actionsSource={actionsSource}
324 style={style}
325 />
326 );
328​
329/**
330 * Attachment thumbnails used by the thread composer and the new-task draft screen.
331 */
332export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) {
333 const size = props.imageSize ?? 72;
334 const radius = props.imageBorderRadius ?? 16;
335 const removeButtonPlacement = props.removeButtonPlacement ?? "overlay";
336 const removeButtonGutter = removeButtonPlacement === "gutter" ? 10 : 0;
337​
338 if (props.attachments.length === 0) {
339 return null;
340 }
341​
342 return (
343 <ScrollView
344 horizontal
345 showsHorizontalScrollIndicator={false}
346 keyboardShouldPersistTaps="always"
347 className="grow-0"
348 >
349 <View className="flex-row gap-2.5">
350 {props.attachments.map((attachment) => (
351 <View
352 key={attachment.id}
353 className="relative"
354 style={{
355 paddingTop: removeButtonGutter,
356 paddingRight: removeButtonGutter,
357 }}
358 >
359 <ComposerAttachmentThumbnail
360 environmentId={props.environmentId}
361 attachment={attachment}
362 size={size}
363 borderRadius={radius}
364 onPressPreview={props.onPressPreview}
365 onPressVideo={props.onPressVideo}
366 onPressDocument={props.onPressDocument}
367 />
368 <Pressable
369 className="absolute h-[22px] w-[22px] items-center justify-center rounded-[11px] bg-black/55"
370 style={{
371 top: removeButtonPlacement === "gutter" ? 0 : 4,
372 right: removeButtonPlacement === "gutter" ? 0 : 4,
373 }}
374 hitSlop={6}
375 onPress={() => props.onRemove(attachment.id)}
376 >
377 <SymbolView
378 name="xmark"
379 size={9}
380 tintColor="#ffffff"
381 type="monochrome"
382 weight="bold"
383 />
384 </Pressable>
385 </View>
386 ))}
387 </View>
388 </ScrollView>
389 );