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