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

QuestionAttachments.tsx

183 lines6.7 KB

1import { TextInputWrapper } from "expo-paste-input";
2import { AppTextInput as TextInput } from "../../components/AppText";
3import { useNativePaste } from "../../lib/useNativePaste";
4import { convertPastedImagesToAttachments } from "../../lib/composerImages";
5import {
6 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
7 type ApprovalRequestId,
8 type UserInputQuestion,
9} from "@t3tools/contracts";
10import { useAtomValue } from "@effect/atom-react";
11import { Alert, View } from "react-native";
12import { useEffect, useRef } from "react";
13import { ComposerAttachmentButton } from "../../components/ComposerAttachmentButton";
14import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
15import { pickComposerFiles, pickComposerMedia } from "../../lib/composerImages";
16import { useThreadSelection } from "../../state/use-thread-selection";
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: ApprovalRequestId;
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 configs = useServerConfigs();
42 const drafts = useAtomValue(composerDraftsAtom);
43 const scopeKey = JSON.stringify([
44 selectedThread?.environmentId,
45 selectedThread?.id,
46 props.requestId,
47 props.question.id,
48 ]);
49 const pickerScope = useRef<{ key: string; active: boolean } | null>(null);
50 useEffect(() => {
51 const scope = { key: scopeKey, active: true };
52 pickerScope.current = scope;
53 return () => {
54 scope.active = false;
55 };
56 }, [scopeKey]);
57 const append = (
58 key: string,
59 attachments: Parameters<typeof appendComposerDraftAttachments>[1],
60 ) => {
61 if (!selectedThread) return 0;
62 const current = appAtomRegistry.get(composerDraftsAtom);
63 const otherCount = props.questions.reduce((count, question) => {
64 const target = questionAttachmentDraftKey(
65 selectedThread.environmentId,
66 selectedThread.id,
67 props.requestId,
68 question.id,
69 );
70 return target === key ? count : count + (current[target]?.attachments.length ?? 0);
71 }, 0);
72 return appendComposerDraftAttachments(key, attachments, {
73 maxAttachments: Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - otherCount),
74 });
75 };
76 const paste = useNativePaste((uris) => {
77 const scope = pickerScope.current;
78 if (
79 !selectedThread ||
80 props.disabled ||
81 !configs.get(selectedThread.environmentId)?.environment.capabilities.questionAttachments
82 )
83 return;
84 const key = questionAttachmentDraftKey(
85 selectedThread.environmentId,
86 selectedThread.id,
87 props.requestId,
88 props.question.id,
89 );
90 changeQuestionAttachmentPreparation(key, 1);
91 void convertPastedImagesToAttachments({
92 uris,
93 existingCount: appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0,
94 })
95 .then(async (images) => {
96 if (
97 scope?.active &&
98 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) > 0
99 ) {
100 if (append(key, images) > 0)
101 Alert.alert("Could not paste image", "Too many attachments.");
102 } else await releaseUnusedComposerAttachmentFiles(images);
103 })
104 .catch((error) =>
105 Alert.alert("Could not paste image", error instanceof Error ? error.message : "Try again."),
106 )
107 .finally(() => changeQuestionAttachmentPreparation(key, -1));
108 });
109 if (!selectedThread || props.question.allowCustomAnswer === false) return null;
110 const { environmentId, id: threadId } = selectedThread;
111 const capabilities = configs.get(environmentId)?.environment.capabilities;
112 const canAttach = capabilities?.questionAttachments === true;
113 const key = questionAttachmentDraftKey(
114 environmentId,
115 threadId,
116 props.requestId,
117 props.question.id,
118 );
119 const attachments = drafts[key]?.attachments ?? [];
120 const pick = async (kind: "media" | "files") => {
121 const scope = pickerScope.current;
122 changeQuestionAttachmentPreparation(key, 1);
123 try {
124 const existingCount = appAtomRegistry.get(composerDraftsAtom)[key]?.attachments.length ?? 0;
125 const result =
126 kind === "files"
127 ? await pickComposerFiles({
128 existingCount,
129 maxBytes: capabilities?.fileAttachments?.maxUploadBytes,
130 })
131 : await pickComposerMedia({
132 existingCount,
133 maxVideoBytes: capabilities?.fileAttachments?.maxUploadBytes,
134 });
135 const picked = "files" in result ? result.files : result.attachments;
136 // Resolution on another client clears the reservation while the picker is open.
137 if (
138 !scope?.active ||
139 (appAtomRegistry.get(questionAttachmentPreparationAtom)[key] ?? 0) === 0
140 ) {
141 await releaseUnusedComposerAttachmentFiles(picked);
142 return;
143 }
144 const rejected = append(key, picked);
145 if (result.error || rejected > 0)
146 Alert.alert("Could not attach file", result.error ?? "Too many attachments.");
147 } catch (error) {
148 Alert.alert("Could not attach file", error instanceof Error ? error.message : "Try again.");
149 } finally {
150 changeQuestionAttachmentPreparation(key, -1);
151 }
152 };
153 return (
154 <View className="gap-2">
155 {canAttach ? (
156 <ComposerAttachmentButton
157 disabled={props.disabled}
158 supportsFiles={Boolean(capabilities?.fileAttachments)}
159 onPickMedia={() => pick("media")}
160 onPickFiles={() => pick("files")}
161 />
162 ) : null}
163 <ComposerAttachmentStrip
164 environmentId={environmentId}
165 attachments={attachments}
166 onRemove={(id) => {
167 if (!props.disabled) removeComposerDraftAttachment(key, id);
168 }}
169 />
170 <TextInputWrapper onPaste={paste}>
171 <TextInput
172 value={props.value}
173 editable={!props.disabled}
174 onChangeText={props.onChangeText}
175 onFocus={() => props.onInputFocusChange?.(true)}
176 onBlur={() => props.onInputFocusChange?.(false)}
177 placeholder="Or type a custom answer"
178 className="min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground"
179 />
180 </TextInputWrapper>
181 </View>
182 );