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