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

QuestionAttachments.tsx

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