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