Open History to see the last commit
1import { Button } from "./ui/Button";
2import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import { AsyncResult } from "effect/reactivity";
4import * as Dialog from "./ui/Dialog";
5import type { ComposerContextRecord, EnvironmentId } from "@t3tools/contracts";
6import { Pressable, View } from "react-native";
7import { Image } from "expo-image";
8import { useEffect, useId, useState } from "react";
9import type { DraftComposerAttachment } from "../lib/composerImages";
10import { composerAttachmentInlineUri, isFileBackedComposerAttachment } from "../lib/composerImages";
11import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
12import { downloadAndShareAttachment } from "../lib/attachmentDownload";
13import { assetImageSource } from "../lib/assetImageSource";
14import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
15import { AppText as Text } from "./ui/AppText";
16import { FilePreviewModal } from "./FilePreviewModal";
17import { PresentationSource } from "./ui/NativePresentation";
18
19export function ComposerContextAttachment(props: {
20 record: Extract<ComposerContextRecord, { attachmentId: string }>;
21 environmentId?: EnvironmentId;
22 attachment?: DraftComposerAttachment;
23}) {
24 const { record, attachment } = props;
25 const shareSourceIdentifier = useId();
26 const resource = {
27 _tag: "attachment" as const,
28 attachmentId: record.attachmentId,
29 fileName: 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 const result = await settlePromise(async () => {
68 if (local) {
69 const preview = await loadLocalAttachmentPreview(local, controller.signal);
70 if (!preview) return;
71 const shared = await settlePromise(() =>
72 preview.share(controller.signal, shareSourceIdentifier),
73 );
74 preview.dispose();
75 if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
76 return;
77 }
78 const url = await refresh();
79 if (!url) throw new Error("Reconnect to the environment and try again.");
80 await downloadAndShareAttachment({
81 url,
82 attachment: record,
83 signal: controller.signal,
84 sourceIdentifier: shareSourceIdentifier,
85 });
86 });
87 setSharing(false);
88 if (AsyncResult.isFailure(result)) {
89 const cause = squashAtomCommandFailure(result);
90 Dialog.alert(
91 "Could not open attachment",
92 cause instanceof Error ? cause.message : "Try again.",
93 );
94 }
95 };
96 return (
97 <View className="gap-3">
98 {record.kind === "image" && uri ? (
99 <Pressable
100 accessibilityRole="button"
101 accessibilityLabel={`Preview ${record.name}`}
102 onPress={() => setPreviewOpen(true)}
103 >
104 <Image
105 source={
106 remoteEnvironmentId === null
107 ? { uri }
108 : assetImageSource(remoteEnvironmentId, resource, uri)
109 }
110 style={{ width: "100%", height: 280 }}
111 contentFit="contain"
112 accessibilityLabel={record.name}
113 />
114 </Pressable>
115 ) : null}
116 {error || (!local && asset._tag === "Failure") ? (
117 <Text className="text-foreground-muted">
118 {error ?? "Attachment unavailable. Reconnect and try again."}
119 </Text>
120 ) : null}
121 <PresentationSource identifier={shareSourceIdentifier}>
122 <Button
123 label={sharing ? "Opening attachment…" : "Open or share attachment"}
124 tone="secondary"
125 disabled={sharing}
126 onPress={() => void share()}
127 fullWidth
128 loading={sharing}
129 />
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}