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

ComposerContextAttachment.tsx

146 lines5.2 KB

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