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