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 focusedRef = useRef(false);
49 const onInputFocusChange = props.onInputFocusChange;
50 // The caller keys this component by request and question, so unmounting ends any open
51 // picker's scope.
52 const pickerScope = useRef<{ active: boolean }>({ active: false });
53 useEffect(() => {
54 const scope = { active: true };
55 pickerScope.current = scope;
56 return () => {
57 scope.active = false;
58 };
59 }, []);
60 // Unmounted inputs never emit onBlur; explicitly release keyboard ownership.
61 const releaseFocus = useEffectEvent(() => {
62 if (focusedRef.current) onInputFocusChange?.(false);
63 });
64 useEffect(() => () => releaseFocus(), []);
65 const append = (
66 key: string,
67 attachments: Parameters<typeof appendComposerDraftAttachments>[1],
68 ) => {
69 if (!selectedThread) return 0;
70 const current = appAtomRegistry.get(composerDraftsAtom);
71 const otherCount = props.questions.reduce((count, question) => {
72 const target = questionAttachmentDraftKey(
73 selectedThread.environmentId,
74 selectedThread.id,
75 props.requestId,
76 question.id,
77 );
78 return target === key ? count : count + (current[target]?.attachments.length ?? 0);
79 }, 0);
80 return appendComposerDraftAttachments(key, attachments, {
81 maxAttachments: Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - otherCount),
82 });
83 };
84 const paste = useNativePaste((uris) => {
85 const scope = pickerScope.current;
86 if (
87 !selectedThread ||
88 props.disabled ||
89 !configs.get(selectedThread.environmentId)?.environment.capabilities.questionAttachments
90 )
91 return;
92 const key = questionAttachmentDraftKey(
93 selectedThread.environmentId,
94 selectedThread.id,
95 props.requestId,
96 props.question.id,
97 );
98 changeQuestionAttachmentPreparation(key, 1);
99 void convertPastedImagesToAttachments({
100 uris,
101 existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,
102 })
103 .then(async (images) => {
104 if (
105 scope.active &&
106 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0
107 ) {
108 if (append(key, images) > 0)
109 Dialog.alert("Could not paste image", "Too many attachments.");
110 } else await releaseUnusedComposerAttachmentFiles(images);
111 })
112 .catch((error) =>
113 Dialog.alert(
114 "Could not paste image",
115 error instanceof Error ? error.message : "Try again.",
116 ),
117 )
118 .finally(() => changeQuestionAttachmentPreparation(key, -1));
119 });
120 if (!selectedThread || props.question.allowCustomAnswer === false) return null;
121 const { environmentId, id: threadId } = selectedThread;
122 const capabilities = configs.get(environmentId)?.environment.capabilities;
123 const canAttach = capabilities?.questionAttachments === true;
124 const key = questionAttachmentDraftKey(
125 environmentId,
126 threadId,
127 props.requestId,
128 props.question.id,
129 );
130 const attachments = drafts[key]?.attachments ?? [];
131 const pick = async (kind: "media" | "files") => {
132 const scope = pickerScope.current;
133 changeQuestionAttachmentPreparation(key, 1);
134 const picked = await settlePromise(async () => {
135 const existingCount = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0;
136 const result =
137 kind === "files"
138 ? await pickComposerFiles({
139 existingCount,
140 maxBytes: capabilities?.fileAttachments?.maxUploadBytes,
141 })
142 : await pickComposerMedia({
143 existingCount,
144 maxVideoBytes: capabilities?.fileAttachments?.maxUploadBytes,
145 });
146 const picked = "files" in result ? result.files : result.attachments;
147 // Resolution on another client clears the reservation while the picker is open.
148 if (
149 !scope.active ||
150 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) === 0
151 ) {
152 await releaseUnusedComposerAttachmentFiles(picked);
153 return;
154 }
155 const rejected = append(key, picked);
156 if (result.error || rejected > 0)
157 Dialog.alert("Could not attach file", result.error ?? "Too many attachments.");
158 });
159 changeQuestionAttachmentPreparation(key, -1);
160 if (AsyncResult.isFailure(picked)) {
161 const error = squashAtomCommandFailure(picked);
162 Dialog.alert("Could not attach file", error instanceof Error ? error.message : "Try again.");
163 }
164 };
165 return (
166 <View className="gap-2">
167 {canAttach ? (
168 <ComposerAttachmentButton
169 disabled={props.disabled}
170 supportsFiles={Boolean(capabilities?.fileAttachments)}
171 onPickMedia={() => pick("media")}
172 onPickFiles={() => pick("files")}
173 />
174 ) : null}
175 <ComposerAttachmentStrip
176 environmentId={environmentId}
177 attachments={attachments}
178 onRemove={(id) => {
179 if (!props.disabled) removeComposerDraftAttachment(key, id);
180 }}
181 onPressPreview={setPreviewFile}
182 onPressVideo={(attachment, sourceIdentifier) =>
183 setPreviewVideo({ type: "local", attachment, sourceIdentifier })
184 }
185 onPressDocument={(attachment) =>
186 navigation.navigate("ThreadAttachment", {
187 environmentId: String(environmentId),
188 threadId: String(threadId),
189 attachmentId: attachment.id,
190 name: attachment.name,
191 mimeType: attachment.mimeType,
192 sizeBytes: String(attachment.sizeBytes),
193 draftKey: key,
194 })
195 }
196 />
197 <FilePreviewModal source={previewFile} onRequestClose={() => setPreviewFile(null)} />
198 <VideoPreviewModal source={previewVideo} onRequestClose={() => setPreviewVideo(null)} />
199 <TextInputWrapper onPaste={paste}>
200 <TextInput
201 value={props.value}
202 multiline={props.question.initialAnswer !== undefined}
203 submitBehavior={props.question.initialAnswer !== undefined ? "newline" : undefined}
204 editable={!props.disabled}
205 onChangeText={props.onChangeText}
206 onFocus={() => {
207 focusedRef.current = true;
208 onInputFocusChange?.(true);
209 }}
210 onBlur={() => {
211 focusedRef.current = false;
212 onInputFocusChange?.(false);
213 }}
214 placeholder="Or type a custom answer"
215 className="min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground"
216 />
217 </TextInputWrapper>
218 </View>
219 );
220}