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