Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

QuestionAttachments.tsx

222 lines8.7 KB

1import * as Dialog from "../../components/ui/Dialog";
2import { TextInputWrapper } from "expo-paste-input";
3import { AppTextInput as TextInput } from "../../components/ui/AppText";
4import { useNativePaste } from "../../lib/useNativePaste";
5import { convertPastedImagesToAttachments } from "../../lib/composerImages";
6import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type UserInputQuestion } from "@t3tools/contracts";
7import { useAtomValue } from "@effect/atom-react";
8import { View } from "react-native";
9import { useEffect, useEffectEvent, useRef, useState } from "react";
10import { ComposerAttachmentButton } from "./ComposerAttachmentButton";
11import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
12import { pickComposerFiles, pickComposerMedia } from "../../lib/composerImages";
13import { useThreadSelection } from "../../state/use-thread-selection";
14import { useNavigation } from "@react-navigation/native";
15import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
16import { VideoPreviewModal, type VideoPreviewSource } from "../../components/VideoPreviewModal";
17import { useServerConfigs } from "../../state/entities";
18import { appAtomRegistry } from "../../state/atom-registry";
19import {
20 appendComposerDraftAttachments,
21 composerDraftsAtom,
22 removeComposerDraftAttachment,
23 releaseUnusedComposerAttachmentFiles,
24} from "../../state/use-composer-drafts";
25import {
26 changeQuestionAttachmentPreparation,
27 questionAttachmentDraftKey,
28 questionAttachmentPreparationAtom,
29} from "../../state/question-attachments";
30​
31export function QuestionAttachments(props: {
32 requestId: string;
33 question: UserInputQuestion;
34 questions: ReadonlyArray<UserInputQuestion>;
35 disabled: boolean;
36 value: string;
37 onChangeText: (value: string) => void;
38 onInputFocusChange?: ((focused: boolean) => void) | undefined;
39}) {
40 const { selectedThread } = useThreadSelection();
41 const navigation = useNavigation();
42 const [previewFile, setPreviewFile] = useState<FilePreviewSource | null>(null);
43 const [previewVideo, setPreviewVideo] = useState<VideoPreviewSource | null>(null);
44 const configs = useServerConfigs();
45 const drafts = useAtomValue(composerDraftsAtom);
46 const scopeKey = JSON.stringify([
47 selectedThread?.environmentId,
48 selectedThread?.id,
49 props.requestId,
50 props.question.id,
51 ]);
52 // A focused input that unmounts never delivers its onBlur, so release focus here or
53 // the screen would keep treating the keyboard as owned by a removed input.
54 const focusedRef = useRef(false);
55 const onInputFocusChange = props.onInputFocusChange;
56 const releaseFocus = useEffectEvent(() => {
57 if (focusedRef.current) onInputFocusChange?.(false);
58 });
59 useEffect(() => () => releaseFocus(), []);
60 const pickerScope = useRef<{ key: string; active: boolean } | null>(null);
61 useEffect(() => {
62 const scope = { key: scopeKey, active: true };
63 pickerScope.current = scope;
64 return () => {
65 scope.active = false;
66 };
67 }, [scopeKey]);
68 const append = (
69 key: string,
70 attachments: Parameters<typeof appendComposerDraftAttachments>[1],
71 ) => {
72 if (!selectedThread) return 0;
73 const current = appAtomRegistry.get(composerDraftsAtom);
74 const otherCount = props.questions.reduce((count, question) => {
75 const target = questionAttachmentDraftKey(
76 selectedThread.environmentId,
77 selectedThread.id,
78 props.requestId,
79 question.id,
80 );
81 return target === key ? count : count + (current[target]?.attachments.length ?? 0);
82 }, 0);
83 return appendComposerDraftAttachments(key, attachments, {
84 maxAttachments: Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - otherCount),
85 });
86 };
87 const paste = useNativePaste((uris) => {
88 const scope = pickerScope.current;
89 if (
90 !selectedThread ||
91 props.disabled ||
92 !configs.get(selectedThread.environmentId)?.environment.capabilities.questionAttachments
93 )
94 return;
95 const key = questionAttachmentDraftKey(
96 selectedThread.environmentId,
97 selectedThread.id,
98 props.requestId,
99 props.question.id,
100 );
101 changeQuestionAttachmentPreparation(key, 1);
102 void convertPastedImagesToAttachments({
103 uris,
104 existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,
105 })
106 .then(async (images) => {
107 if (
108 scope?.active &&
109 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0
110 ) {
111 if (append(key, images) > 0)
112 Dialog.alert("Could not paste image", "Too many attachments.");
113 } else await releaseUnusedComposerAttachmentFiles(images);
114 })
115 .catch((error) =>
116 Dialog.alert(
117 "Could not paste image",
118 error instanceof Error ? error.message : "Try again.",
119 ),
120 )
121 .finally(() => changeQuestionAttachmentPreparation(key, -1));
122 });
123 if (!selectedThread || props.question.allowCustomAnswer === false) return null;
124 const { environmentId, id: threadId } = selectedThread;
125 const capabilities = configs.get(environmentId)?.environment.capabilities;
126 const canAttach = capabilities?.questionAttachments === true;
127 const key = questionAttachmentDraftKey(
128 environmentId,
129 threadId,
130 props.requestId,
131 props.question.id,
132 );
133 const attachments = drafts[key]?.attachments ?? [];
134 const pick = async (kind: "media" | "files") => {
135 const scope = pickerScope.current;
136 changeQuestionAttachmentPreparation(key, 1);
137 try {
138 const existingCount = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0;
139 const result =
140 kind === "files"
141 ? await pickComposerFiles({
142 existingCount,
143 maxBytes: capabilities?.fileAttachments?.maxUploadBytes,
144 })
145 : await pickComposerMedia({
146 existingCount,
147 maxVideoBytes: capabilities?.fileAttachments?.maxUploadBytes,
148 });
149 const picked = "files" in result ? result.files : result.attachments;
150 // Resolution on another client clears the reservation while the picker is open.
151 if (
152 !scope?.active ||
153 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) === 0
154 ) {
155 await releaseUnusedComposerAttachmentFiles(picked);
156 return;
157 }
158 const rejected = append(key, picked);
159 if (result.error || rejected > 0)
160 Dialog.alert("Could not attach file", result.error ?? "Too many attachments.");
161 } catch (error) {
162 Dialog.alert("Could not attach file", error instanceof Error ? error.message : "Try again.");
163 } finally {
164 changeQuestionAttachmentPreparation(key, -1);
165 }
166 };
167 return (
168 <View className="gap-2">
169 {canAttach ? (
170 <ComposerAttachmentButton
171 disabled={props.disabled}
172 supportsFiles={Boolean(capabilities?.fileAttachments)}
173 onPickMedia={() => pick("media")}
174 onPickFiles={() => pick("files")}
175 />
176 ) : null}
177 <ComposerAttachmentStrip
178 environmentId={environmentId}
179 attachments={attachments}
180 onRemove={(id) => {
181 if (!props.disabled) removeComposerDraftAttachment(key, id);
182 }}
183 onPressPreview={setPreviewFile}
184 onPressVideo={(attachment, sourceIdentifier) =>
185 setPreviewVideo({ type: "local", attachment, sourceIdentifier })
186 }
187 onPressDocument={(attachment) =>
188 navigation.navigate("ThreadAttachment", {
189 environmentId: String(environmentId),
190 threadId: String(threadId),
191 attachmentId: attachment.id,
192 name: attachment.name,
193 mimeType: attachment.mimeType,
194 sizeBytes: String(attachment.sizeBytes),
195 draftKey: key,
196 })
197 }
198 />
199 <FilePreviewModal source={previewFile} onRequestClose={() => setPreviewFile(null)} />
200 <VideoPreviewModal source={previewVideo} onRequestClose={() => setPreviewVideo(null)} />
201 <TextInputWrapper onPaste={paste}>
202 <TextInput
203 value={props.value}
204 multiline={props.question.initialAnswer !== undefined}
205 submitBehavior={props.question.initialAnswer !== undefined ? "newline" : undefined}
206 editable={!props.disabled}
207 onChangeText={props.onChangeText}
208 onFocus={() => {
209 focusedRef.current = true;
210 onInputFocusChange?.(true);
211 }}
212 onBlur={() => {
213 focusedRef.current = false;
214 onInputFocusChange?.(false);
215 }}
216 placeholder="Or type a custom answer"
217 className="min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground"
218 />
219 </TextInputWrapper>
220 </View>
221 );