Open History to see the last commit
1import * as Dialog from "./ui/Dialog";
2import type { ComposerContextRecord, EnvironmentId } from "@t3tools/contracts";
3import { Pressable, View } from "react-native";
4import { Image } from "expo-image";
5import { useEffect, useId, useMemo, useState } from "react";
6import type { DraftComposerAttachment } from "../lib/composerImages";
7import { composerAttachmentInlineUri, isFileBackedComposerAttachment } from "../lib/composerImages";
8import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
9import { downloadAndShareAttachment } from "../lib/attachmentDownload";
10import { assetImageSource } from "../lib/assetImageSource";
11import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
12import { AppText as Text } from "./ui/AppText";
13import { FilePreviewModal } from "./FilePreviewModal";
14import { PresentationSource } from "./ui/NativePresentation";
15
16export function ComposerContextAttachment(props: {
17 record: Extract<ComposerContextRecord, { attachmentId: string }>;
18 environmentId?: EnvironmentId;
19 attachment?: DraftComposerAttachment;
20}) {
21 const { record, attachment } = props;
22 const shareSourceIdentifier = useId();
23 const resource = useMemo(
24 () => ({
25 _tag: "attachment" as const,
26 attachmentId: record.attachmentId,
27 fileName: record.name,
28 }),
29 [record.attachmentId, record.name],
30 );
31 const local = attachment?.fileUri
32 ? (attachment as DraftComposerAttachment & { fileUri: string })
33 : undefined;
34 const inlineUri = composerAttachmentInlineUri(attachment);
35 const remoteEnvironmentId = local || inlineUri ? null : (props.environmentId ?? null);
36 const asset = useAssetUrlState(remoteEnvironmentId, resource);
37 const refresh = useRefreshAssetUrl(remoteEnvironmentId, resource);
38 const [localUri, setLocalUri] = useState<string | null>(null);
39 const [error, setError] = useState<string | null>(null);
40 const [sharing, setSharing] = useState(false);
41 const [previewOpen, setPreviewOpen] = useState(false);
42 useEffect(() => {
43 if (!local) return;
44 const controller = new AbortController();
45 let dispose: (() => void) | undefined;
46 void loadLocalAttachmentPreview(local, controller.signal)
47 .then((preview) => {
48 if (!preview) return;
49 if (controller.signal.aborted) return preview.dispose();
50 dispose = preview.dispose;
51 setLocalUri(preview.uri);
52 setError(null);
53 })
54 .catch(() => {
55 if (!controller.signal.aborted) setError("The local file is unavailable. Attach it again.");
56 });
57 return () => {
58 controller.abort();
59 dispose?.();
60 };
61 }, [local]);
62 const uri = local ? localUri : (inlineUri ?? (asset._tag === "Success" ? asset.url : null));
63 const share = async () => {
64 if (sharing) return;
65 setSharing(true);
66 const controller = new AbortController();
67 try {
68 if (local) {
69 const preview = await loadLocalAttachmentPreview(local, controller.signal);
70 try {
71 await preview?.share(controller.signal, shareSourceIdentifier);
72 } finally {
73 preview?.dispose();
74 }
75 } else {
76 const url = await refresh();
77 if (!url) throw new Error("Reconnect to the environment and try again.");
78 await downloadAndShareAttachment({
79 url,
80 attachment: record,
81 signal: controller.signal,
82 sourceIdentifier: shareSourceIdentifier,
83 });
84 }
85 } catch (cause) {
86 Dialog.alert(
87 "Could not open attachment",
88 cause instanceof Error ? cause.message : "Try again.",
89 );
90 } finally {
91 setSharing(false);
92 }
93 };
94 return (
95 <View className="gap-3">
96 {record.kind === "image" && uri ? (
97 <Pressable
98 accessibilityRole="button"
99 accessibilityLabel={`Preview ${record.name}`}
100 onPress={() => setPreviewOpen(true)}
101 >
102 <Image
103 source={
104 remoteEnvironmentId === null
105 ? { uri }
106 : assetImageSource(remoteEnvironmentId, resource, uri)
107 }
108 style={{ width: "100%", height: 280 }}
109 contentFit="contain"
110 accessibilityLabel={record.name}
111 />
112 </Pressable>
113 ) : null}
114 {error || (!local && asset._tag === "Failure") ? (
115 <Text className="text-foreground-muted">
116 {error ?? "Attachment unavailable. Reconnect and try again."}
117 </Text>
118 ) : null}
119 <PresentationSource identifier={shareSourceIdentifier}>
120 <Pressable
121 accessibilityRole="button"
122 disabled={sharing}
123 onPress={() => void share()}
124 className="rounded-xl bg-subtle p-4"
125 >
126 <Text className="text-foreground">
127 {sharing ? "Opening attachment…" : "Open or share attachment"}
128 </Text>
129 </Pressable>
130 </PresentationSource>
131 {previewOpen && record.kind === "image" && uri ? (
132 <FilePreviewModal
133 source={{
134 kind: "image",
135 name: record.name,
136 uri,
137 actionsSource: {
138 name: record.name,
139 mimeType: record.mimeType,
140 ...(attachment && isFileBackedComposerAttachment(attachment)
141 ? { attachment }
142 : inlineUri === undefined && props.environmentId
143 ? { environmentId: props.environmentId, resource }
144 : { uri }),
145 },
146 }}
147 onRequestClose={() => setPreviewOpen(false)}
148 />
149 ) : null}
150 </View>
151 );
152}