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

QuestionAttachments.tsx

217 lines8.9 KB

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