Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { TextInputWrapper } from "expo-paste-input";
3import { AppTextInput as TextInput } from "../../components/ui/AppText";
4import { useNativePaste } from "../../lib/useNativePaste";
5import { convertPastedImagesToAttachments } from "../../lib/composerImages";
6import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type UserInputQuestion } from "@t3tools/contracts";
7import { useAtomValue } from "@effect/atom-react";
8import { View } from "react-native";
9import { useEffect, useRef, useState } from "react";
10import { ComposerAttachmentButton } from "./ComposerAttachmentButton";
11import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
12import { pickComposerFiles, pickComposerMedia } from "../../lib/composerImages";
13import { useThreadSelection } from "../../state/use-thread-selection";
14import { useNavigation } from "@react-navigation/native";
15import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
16import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
17import { useServerConfigs } from "../../state/entities";
18import { appAtomRegistry } from "../../state/atom-registry";
19import {
20 appendComposerDraftAttachments,
21 composerDraftsAtom,
22 removeComposerDraftAttachment,
23 releaseUnusedComposerAttachmentFiles,
24} from "../../state/use-composer-drafts";
25import {
26 changeQuestionAttachmentPreparation,
27 questionAttachmentDraftKey,
28 questionAttachmentPreparationAtom,
29} from "../../state/question-attachments";
30
31export function QuestionAttachments(props: {
32 requestId: string;
33 question: UserInputQuestion;
34 questions: ReadonlyArray<UserInputQuestion>;
35 disabled: boolean;
36 value: string;
37 onChangeText: (value: string) => void;
38 onInputFocusChange?: ((focused: boolean) => void) | undefined;
39}) {
40 const { selectedThread } = useThreadSelection();
41 const navigation = useNavigation();
42 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
43 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
44 const configs = useServerConfigs();
45 const drafts = useAtomValue(composerDraftsAtom);
46 const scopeKey = JSON.stringify([
47 selectedThread?.environmentId,
48 selectedThread?.id,
49 props.requestId,
50 props.question.id,
51 ]);
52 const pickerScope = useRef<{ key: string; active: boolean } | null>(null);
53 useEffect(() => {
54 const scope = { key: scopeKey, active: true };
55 pickerScope.current = scope;
56 return () => {
57 scope.active = false;
58 };
59 }, [scopeKey]);
60 const append = (
61 key: string,
62 attachments: Parameters<typeof appendComposerDraftAttachments>[1],
63 ) => {
64 if (!selectedThread) return 0;
65 const current = appAtomRegistry.get(composerDraftsAtom);
66 const otherCount = props.questions.reduce((count, question) => {
67 const target = questionAttachmentDraftKey(
68 selectedThread.environmentId,
69 selectedThread.id,
70 props.requestId,
71 question.id,
72 );
73 return target === key ? count : count + (current[target]?.attachments.length ?? 0);
74 }, 0);
75 return appendComposerDraftAttachments(key, attachments, {
76 maxAttachments: Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - otherCount),
77 });
78 };
79 const paste = useNativePaste((uris) => {
80 const scope = pickerScope.current;
81 if (
82 !selectedThread ||
83 props.disabled ||
84 !configs.get(selectedThread.environmentId)?.environment.capabilities.questionAttachments
85 )
86 return;
87 const key = questionAttachmentDraftKey(
88 selectedThread.environmentId,
89 selectedThread.id,
90 props.requestId,
91 props.question.id,
92 );
93 changeQuestionAttachmentPreparation(key, 1);
94 void convertPastedImagesToAttachments({
95 uris,
96 existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,
97 })
98 .then(async (images) => {
99 if (
100 scope?.active &&
101 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0
102 ) {
103 if (append(key, images) > 0)
104 Dialog.alert("Could not paste image", "Too many attachments.");
105 } else await releaseUnusedComposerAttachmentFiles(images);
106 })
107 .catch((error) =>
108 Dialog.alert(
109 "Could not paste image",
110 error instanceof Error ? error.message : "Try again.",
111 ),
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 Dialog.alert("Could not attach file", result.error ?? "Too many attachments.");
153 } catch (error) {
154 Dialog.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 multiline={props.question.initialAnswer !== undefined}
197 submitBehavior={props.question.initialAnswer !== undefined ? "newline" : undefined}
198 editable={!props.disabled}
199 onChangeText={props.onChangeText}
200 onFocus={() => props.onInputFocusChange?.(true)}
201 onBlur={() => props.onInputFocusChange?.(false)}
202 placeholder="Or type a custom answer"
203 className="min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground"
204 />
205 </TextInputWrapper>
206 </View>
207 );
208}