Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import { QuestionAttachments } from "./QuestionAttachments";
3import type { RuntimeRequestId } from "@t3tools/contracts";
4import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
5import { useCallback, useRef } from "react";
6import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
7import Animated, {
8 Easing,
9 FadeInUp,
10 FadeOutDown,
11 useAnimatedStyle,
12 useSharedValue,
13 type DerivedValue,
14 type SharedValue,
15} from "react-native-reanimated";
16
17import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
18
19import { SymbolView } from "../../components/ui/AppSymbol";
20import { AppText as Text } from "../../components/ui/AppText";
21import { ControlPill } from "../../components/ui/ControlPill";
22import { cn } from "../../lib/cn";
23import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
24import { useOpenPullRequest } from "../../native/useOpenPullRequest";
25import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";
26import {
27 isPendingUserInputOptionSelected,
28 type PendingUserInput,
29 type PendingUserInputDraftAnswer,
30} from "../../lib/threadActivity";
31
32export interface PendingUserInputCardProps {
33 readonly canOperateThread: boolean;
34 readonly pendingUserInput: PendingUserInput;
35 readonly maxHeight: DerivedValue<number>;
36 readonly collapsed: boolean;
37 readonly onToggleCollapsed: () => void;
38 readonly onStopThread?: () => void;
39 readonly cardProgress?: SharedValue<number>;
40 readonly cardCoverage?: SharedValue<number>;
41 readonly onInputFocusChange?: (focused: boolean) => void;
42 readonly drafts: Record<string, PendingUserInputDraftAnswer>;
43 readonly answers: Record<string, string | ReadonlyArray<string>> | null;
44 readonly respondingUserInputId: RuntimeRequestId | null;
45 readonly onSelectOption: (
46 requestId: RuntimeRequestId,
47 question: ThreadUserInputQuestion,
48 value: string,
49 ) => void;
50 readonly onChangeCustomAnswer: (
51 requestId: RuntimeRequestId,
52 questionId: string,
53 customAnswer: string,
54 ) => void;
55 readonly onSubmit: () => Promise<unknown>;
56 readonly onDismiss: () => Promise<unknown>;
57}
58
59/**
60 * Android cannot use the overlay: it does not hit-test touches outside a
61 * parent's bounds, which made everything above the bar-sized wrapper
62 * untouchable.
63 */
64const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
65
66function QuestionText(props: { readonly markdown: string }) {
67 const styles = useMarkdownPreviewStyles();
68 const openLink = useOpenPullRequest();
69 return (
70 <SelectableMarkdownText
71 markdown={props.markdown}
72 textStyle={styles.nativeTextStyle}
73 onLinkPress={(href) => void openLink(href)}
74 />
75 );
76}
77
78export function PendingUserInputCard(props: PendingUserInputCardProps) {
79 const questionCount = props.pendingUserInput.questions.length;
80 const canRespond = props.pendingUserInput.responseCapability !== "not_resumable";
81 const isResponding = props.respondingUserInputId === props.pendingUserInput.requestId;
82 const responseDisabled = !canRespond || isResponding;
83
84 const cardCoverage = props.cardCoverage;
85 const barHeightRef = useRef(0);
86 const cardHeightRef = useRef(0);
87 const cardHeight = useSharedValue(0);
88 const notifyCoverage = useCallback(() => {
89 if (!cardCoverage) {
90 return;
91 }
92 // The card resizes with the keyboard every frame, so easing each sample would leave the
93 // feed inset and floating controls trailing it.
94 cardCoverage.value = Math.max(0, cardHeightRef.current - barHeightRef.current);
95 }, [cardCoverage]);
96 const handleBarLayout = useCallback(
97 (event: LayoutChangeEvent) => {
98 barHeightRef.current = event.nativeEvent.layout.height;
99 notifyCoverage();
100 },
101 [notifyCoverage],
102 );
103 const handleCardLayout = useCallback(
104 (event: LayoutChangeEvent) => {
105 cardHeightRef.current = event.nativeEvent.layout.height;
106 cardHeight.value = event.nativeEvent.layout.height;
107 notifyCoverage();
108 },
109 [cardHeight, notifyCoverage],
110 );
111 const cardProgress = props.cardProgress;
112 const maxHeight = props.maxHeight;
113 const cardAnimatedStyle = useAnimatedStyle(() => {
114 const progress = cardProgress === undefined ? 1 : cardProgress.value;
115 return {
116 maxHeight: maxHeight.value,
117 transform: [{ translateY: (1 - progress) * cardHeight.value }],
118 };
119 });
120 const cardMaxHeightStyle = useAnimatedStyle(() => ({ maxHeight: maxHeight.value }));
121 const overlayHeightStyle = useAnimatedStyle(() => ({ height: maxHeight.value }));
122
123 // On iOS the card stays MOUNTED while collapsed (hidden via the animated
124 // style): expanding animates existing views on the UI thread the same
125 // frame the host starts the progress timing, instead of paying a React
126 // mount + layout before anything moves.
127 const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
128 const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
129 const bar = showBar ? (
130 <View
131 onLayout={handleBarLayout}
132 pointerEvents={props.collapsed ? "auto" : "none"}
133 accessibilityElementsHidden={!props.collapsed}
134 importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
135 className="flex-row items-center gap-2 rounded-full border border-border bg-card-alt py-1.5 pl-4 pr-1.5"
136 >
137 <Pressable
138 accessibilityRole="button"
139 accessibilityLabel={`Expand user input, ${questionCount} question${
140 questionCount === 1 ? "" : "s"
141 }`}
142 onPress={props.onToggleCollapsed}
143 className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
144 >
145 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
146 User input needed
147 </Text>
148 <Text className="font-sans text-xs text-foreground-muted">
149 {questionCount} question{questionCount === 1 ? "" : "s"}
150 </Text>
151 <View className="flex-1" />
152 <SymbolView
153 name="chevron.up"
154 size={12}
155 tintColorClassName={"accent-icon-subtle"}
156 type="monochrome"
157 />
158 </Pressable>
159 {props.onStopThread ? (
160 <ControlPill
161 accessibilityLabel="Stop"
162 icon="stop.fill"
163 variant="danger"
164 className="h-9 w-9"
165 disabled={!props.canOperateThread}
166 onPress={props.onStopThread}
167 />
168 ) : null}
169 </View>
170 ) : null;
171 const card = renderCard ? (
172 <Animated.View
173 onLayout={handleCardLayout}
174 pointerEvents={props.collapsed ? "none" : "auto"}
175 accessibilityElementsHidden={props.collapsed}
176 importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
177 entering={
178 EXPANDED_CARD_IS_OVERLAY
179 ? undefined
180 : FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
181 }
182 exiting={
183 EXPANDED_CARD_IS_OVERLAY
184 ? undefined
185 : FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
186 }
187 className="overflow-hidden gap-2.5 rounded-[20px] border border-border bg-card-alt p-4"
188 style={EXPANDED_CARD_IS_OVERLAY ? cardAnimatedStyle : cardMaxHeightStyle}
189 >
190 <Pressable
191 accessibilityRole="button"
192 accessibilityLabel="Collapse user input"
193 onPress={props.onToggleCollapsed}
194 className="flex-row items-start gap-2"
195 >
196 <View className="flex-1 gap-2.5">
197 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
198 User input needed
199 </Text>
200 <Text className="font-t3-bold text-lg text-foreground">Fill in the pending answers</Text>
201 </View>
202 <View className="h-8 w-8 items-center justify-center rounded-full bg-subtle-strong">
203 <SymbolView
204 name="chevron.down"
205 size={13}
206 tintColorClassName={"accent-icon-subtle"}
207 type="monochrome"
208 />
209 </View>
210 </Pressable>
211 <ScrollView
212 bounces={false}
213 className="min-h-0"
214 contentContainerClassName="gap-2.5 pb-1"
215 keyboardShouldPersistTaps="handled"
216 nestedScrollEnabled
217 showsVerticalScrollIndicator
218 style={{ flexShrink: 1 }}
219 >
220 {!canRespond ? (
221 <Text className="font-sans text-sm leading-5 text-foreground-muted">
222 The provider process for this request is no longer available. Interrupt or restart the
223 run to continue.
224 </Text>
225 ) : null}
226 {props.pendingUserInput.questions.map((question) => {
227 const draft = props.drafts[question.id];
228 return (
229 <View key={question.id} className="gap-2 pt-1">
230 <Text className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted">
231 {question.header}
232 </Text>
233 <QuestionText markdown={question.question} />
234 <View className="gap-2">
235 {question.options.map((option) => {
236 const optionValue = option.value ?? option.label.trim();
237 const selected = isPendingUserInputOptionSelected(question, draft, optionValue);
238 const description =
239 option.description !== option.label ? option.description : undefined;
240 return (
241 <Pressable
242 key={optionValue}
243 accessibilityRole={question.multiSelect ? "checkbox" : "radio"}
244 accessibilityState={{ checked: selected, disabled: responseDisabled }}
245 disabled={responseDisabled}
246 className={cn(
247 "min-h-12 w-full rounded-2xl border px-3.5 py-3",
248 selected ? "border-primary bg-primary/10" : "border-border bg-input",
249 )}
250 onPress={() =>
251 props.onSelectOption(
252 props.pendingUserInput.requestId,
253 question,
254 optionValue,
255 )
256 }
257 >
258 <View className="min-w-0 flex-1 gap-0.5">
259 <Text
260 className={cn(
261 "font-t3-bold text-sm",
262 selected ? "text-foreground" : "text-foreground-secondary",
263 )}
264 >
265 {option.label}
266 </Text>
267 {description ? (
268 <Text className="font-sans text-sm leading-5 text-foreground-muted">
269 {description}
270 </Text>
271 ) : null}
272 </View>
273 </Pressable>
274 );
275 })}
276 </View>
277 {question.allowCustomAnswer !== false ? (
278 <QuestionAttachments
279 requestId={props.pendingUserInput.requestId}
280 question={question}
281 questions={props.pendingUserInput.questions}
282 disabled={responseDisabled}
283 value={draft?.customAnswer ?? ""}
284 onChangeText={(value) =>
285 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
286 }
287 onInputFocusChange={props.onInputFocusChange}
288 />
289 ) : null}
290 </View>
291 );
292 })}
293 </ScrollView>
294 <Button
295 label="Submit answers"
296 fullWidth
297 tone={props.answers ? "primary" : "secondary"}
298 disabled={!props.canOperateThread || responseDisabled || props.answers === null}
299 onPress={() => void props.onSubmit()}
300 />
301 {props.pendingUserInput.dismissible ? (
302 <Button
303 label="Dismiss without answering"
304 tone="text"
305 disabled={isResponding}
306 onPress={() => void props.onDismiss()}
307 />
308 ) : null}
309 {!props.canOperateThread ? (
310 <Text className="font-sans text-xs text-foreground-tertiary">
311 This connection cannot submit answers.
312 </Text>
313 ) : null}
314 </Animated.View>
315 ) : null;
316 return (
317 <View className="relative">
318 {bar}
319 {EXPANDED_CARD_IS_OVERLAY ? (
320 <Animated.View
321 pointerEvents={props.collapsed ? "none" : "box-none"}
322 className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
323 style={overlayHeightStyle}
324 >
325 {card}
326 </Animated.View>
327 ) : (
328 card
329 )}
330 </View>
331 );
332}