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