Open History to see the last commit
1import { TextInputWrapper } from "expo-paste-input";
2import { AppTextInput as TextInput } from "../../components/AppText";
3import { useNativePaste } from "../../lib/useNativePaste";
4import { convertPastedImagesToAttachments } from "../../lib/composerImages";
5import {
6 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
7 type ApprovalRequestId,
8 type UserInputQuestion,
9} from "@t3tools/contracts";
10import { useAtomValue } from "@effect/atom-react";
11import { Alert, View } from "react-native";
12import { useEffect, useRef, useState } from "react";
13import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
14import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
15import { pickComposerFiles, pickComposerMedia } from "../../lib/composerImages";
16import { useThreadSelection } from "../../state/use-thread-selection";
17import { useNavigation } from "@react-navigation/native";
18import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
19import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
20import { useServerConfigs } from "../../state/entities";
21import { appAtomRegistry } from "../../state/atom-registry";
22import {
23 appendComposerDraftAttachments,
24 composerDraftsAtom,
25 removeComposerDraftAttachment,
26 releaseUnusedComposerAttachmentFiles,
27} from "../../state/use-composer-drafts";
28import {
29 changeQuestionAttachmentPreparation,
30 questionAttachmentDraftKey,
31 questionAttachmentPreparationAtom,
32} from "../../state/question-attachments";
33
34export function QuestionAttachments(props: {
35 requestId: ApprovalRequestId;
36 question: UserInputQuestion;
37 questions: ReadonlyArray<UserInputQuestion>;
38 disabled: boolean;
39 value: string;
40 onChangeText: (value: string) => void;
41 onInputFocusChange?: ((focused: boolean) => void) | undefined;
42}) {
43 const { selectedThread } = useThreadSelection();
44 const navigation = useNavigation();
45 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
46 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
47 const configs = useServerConfigs();
48 const drafts = useAtomValue(composerDraftsAtom);
49 const scopeKey = JSON.stringify([
50 selectedThread?.environmentId,
51 selectedThread?.id,
52 props.requestId,
53 props.question.id,
54 ]);
55 const pickerScope = useRef<{ key: string; active: boolean } | null>(null);
56 useEffect(() => {
57 const scope = { key: scopeKey, active: true };
58 pickerScope.current = scope;
59 return () => {
60 scope.active = false;
61 };
62 }, [scopeKey]);
63 const append = (
64 key: string,
65 attachments: Parameters<typeof appendComposerDraftAttachments>[1],
66 ) => {
67 if (!selectedThread) return 0;
68 const current = appAtomRegistry.get(composerDraftsAtom);
69 const otherCount = props.questions.reduce((count, question) => {
70 const target = questionAttachmentDraftKey(
71 selectedThread.environmentId,
72 selectedThread.id,
73 props.requestId,
74 question.id,
75 );
76 return target === key ? count : count + (current[target]?.attachments.length ?? 0);
77 }, 0);
78 return appendComposerDraftAttachments(key, attachments, {
79 maxAttachments: Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - otherCount),
80 });
81 };
82 const paste = useNativePaste((uris) => {
83 const scope = pickerScope.current;
84 if (
85 !selectedThread ||
86 props.disabled ||
87 !configs.get(selectedThread.environmentId)?.environment.capabilities.questionAttachments
88 )
89 return;
90 const key = questionAttachmentDraftKey(
91 selectedThread.environmentId,
92 selectedThread.id,
93 props.requestId,
94 props.question.id,
95 );
96 changeQuestionAttachmentPreparation(key, 1);
97 void convertPastedImagesToAttachments({
98 uris,
99 existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,
100 })
101 .then(async (images) => {
102 if (
103 scope?.active &&
104 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0
105 ) {
106 if (append(key, images) > 0)
107 Alert.alert("Could not paste image", "Too many attachments.");
108 } else await releaseUnusedComposerAttachmentFiles(images);
109 })
110 .catch((error) =>
111 Alert.alert("Could not paste image", error instanceof Error ? error.message : "Try again."),
112 )
113 .finally(() => changeQuestionAttachmentPreparation(key, -1));
114 });
115 if (!selectedThread || props.question.allowCustomAnswer === false) return null;
116 const { environmentId, id: threadId } = selectedThread;
117 const capabilities = configs.get(environmentId)?.environment.capabilities;
118 const canAttach = capabilities?.questionAttachments === true;
119 const key = questionAttachmentDraftKey(
120 environmentId,
121 threadId,
122 props.requestId,
123 props.question.id,
124 );
125 const attachments = drafts[key]?.attachments ?? [];
126 const pick = async (kind: "media" | "files") => {
127 const scope = pickerScope.current;
128 changeQuestionAttachmentPreparation(key, 1);
129 try {
130 const existingCount = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0;
131 const result =
132 kind === "files"
133 ? await pickComposerFiles({
134 existingCount,
135 maxBytes: capabilities?.fileAttachments?.maxUploadBytes,
136 })
137 : await pickComposerMedia({
138 existingCount,
139 maxVideoBytes: capabilities?.fileAttachments?.maxUploadBytes,
140 });
141 const picked = "files" in result ? result.files : result.attachments;
142 // Resolution on another client clears the reservation while the picker is open.
143 if (
144 !scope?.active ||
145 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) === 0
146 ) {
147 await releaseUnusedComposerAttachmentFiles(picked);
148 return;
149 }
150 const rejected = append(key, picked);
151 if (result.error || rejected > 0)
152 Alert.alert("Could not attach file", result.error ?? "Too many attachments.");
153 } catch (error) {
154 Alert.alert("Could not attach file", error instanceof Error ? error.message : "Try again.");
155 } finally {
156 changeQuestionAttachmentPreparation(key, -1);
157 }
158 };
159 return (
160 <View className="gap-2">
161 {canAttach ? (
162 <ComposerAttachmentButton
163 disabled={props.disabled}
164 supportsFiles={Boolean(capabilities?.fileAttachments)}
165 onPickMedia={() => pick("media")}
166 onPickFiles={() => pick("files")}
167 />
168 ) : null}
169 <ComposerAttachmentStrip
170 environmentId={environmentId}
171 attachments={attachments}
172 onRemove={(id) => {
173 if (!props.disabled) removeComposerDraftAttachment(key, id);
174 }}
175 onPressPreview={setPreviewFile}
176 onPressVideo={(attachment, sourceIdentifier) =>
177 setPreviewVideo({ type: "local", attachment, sourceIdentifier })
178 }
179 onPressDocument={(attachment) =>
180 navigation.navigate("ThreadAttachment", {
181 environmentId: String(environmentId),
182 threadId: String(threadId),
183 attachmentId: attachment.id,
184 name: attachment.name,
185 mimeType: attachment.mimeType,
186 sizeBytes: String(attachment.sizeBytes),
187 draftKey: key,
188 })
189 }
190 />
191 <FilePreviewModal source={previewFile} onRequestClose={() => setPreviewFile(null)} />
192 <VideoPreviewModal source={previewVideo} onRequestClose={() => setPreviewVideo(null)} />
193 <TextInputWrapper onPaste={paste}>
194 <TextInput
195 value={props.value}
196 editable={!props.disabled}
197 onChangeText={props.onChangeText}
198 onFocus={() => props.onInputFocusChange?.(true)}
199 onBlur={() => props.onInputFocusChange?.(false)}
200 placeholder="Or type a custom answer"
201 className="min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground"
202 />
203 </TextInputWrapper>
204 </View>
205 );
206}