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