Open History to see the last commit
1import { RequestActionButton } from "./RequestActionButton";
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 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/AppSymbol";
21import { AppText as Text } from "../../components/AppText";
22import { ControlPill } from "../../components/ControlPill";
23import { cn } from "../../lib/cn";
24import {
25 isPendingUserInputOptionSelected,
26 type PendingUserInput,
27 type PendingUserInputDraftAnswer,
28} from "../../lib/threadActivity";
29
30export interface PendingUserInputCardProps {
31 readonly pendingUserInput: PendingUserInput;
32 /**
33 * Constant while a request is pending (it reserves keyboard space), so the
34 * keyboard transition is pure translation; changes only on rare discrete
35 * corrections, which the layout transition smooths.
36 */
37 readonly maxHeight: number;
38 readonly collapsed: boolean;
39 readonly onToggleCollapsed: () => void;
40 /** Renders a stop control on the collapsed bar, which replaces the composer. */
41 readonly onStopThread?: () => void;
42 /**
43 * 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the
44 * collapsed bar (inside a clipping window) on the UI thread; the host
45 * animates it directly from the tap handler so the card and the feed
46 * inset glide start the same frame.
47 */
48 readonly cardProgress?: SharedValue<number>;
49 /**
50 * Receives how far the expanded card extends above the bar footprint
51 * (written from onLayout with no re-render); the host adds it to the
52 * thread feed's end inset so the end of the chat stays visible above the
53 * card.
54 */
55 readonly cardCoverage?: SharedValue<number>;
56 /** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */
57 readonly onInputFocusChange?: (focused: boolean) => void;
58 readonly drafts: Record<string, PendingUserInputDraftAnswer>;
59 readonly answers: Record<string, string | ReadonlyArray<string>> | null;
60 readonly respondingUserInputId: RuntimeRequestId | null;
61 readonly onSelectOption: (
62 requestId: RuntimeRequestId,
63 question: ThreadUserInputQuestion,
64 value: string,
65 ) => void;
66 readonly onChangeCustomAnswer: (
67 requestId: RuntimeRequestId,
68 questionId: string,
69 customAnswer: string,
70 ) => void;
71 readonly onSubmit: () => Promise<unknown>;
72 /** Closes an async question without a reply. Hidden for native callback questions. */
73 readonly onDismiss: () => Promise<unknown>;
74}
75
76/**
77 * On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
78 * card is an absolutely-positioned overlay rising above it. The overlay's
79 * measured height (which drives the thread feed's bottom inset) therefore
80 * never changes on collapse/expand, so the transcript stays perfectly still
81 * while the card animates over it.
82 *
83 * Android cannot use the overlay: it does not hit-test touches outside a
84 * parent's bounds, which made everything above the bar-sized wrapper
85 * untouchable. There the expanded card renders in-flow instead (the wrapper
86 * grows with it, and the host skips the coverage inset since the measured
87 * overlay already includes the card).
88 */
89const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
90
91const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
92
93export function PendingUserInputCard(props: PendingUserInputCardProps) {
94 const questionCount = props.pendingUserInput.questions.length;
95 // Message responses start a new run and remain available after the provider exits.
96 const canRespond = props.pendingUserInput.responseCapability !== "not_resumable";
97 const isResponding = props.respondingUserInputId === props.pendingUserInput.requestId;
98 const responseDisabled = !canRespond || isResponding;
99
100 const cardCoverage = props.cardCoverage;
101 const barHeightRef = useRef(0);
102 const cardHeightRef = useRef(0);
103 // Measured card height, written straight from onLayout: the collapse slide
104 // distance. Not animated — it only changes on discrete relayouts.
105 const cardHeight = useSharedValue(0);
106 const notifyCoverage = useCallback(() => {
107 if (!cardCoverage) {
108 return;
109 }
110 const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
111 if (coverage === cardCoverage.value) {
112 return;
113 }
114 if (cardCoverage.value === 0) {
115 // First measurement lands while the list is doing its initial
116 // end-pin (thread opened onto a pending request); animating it from
117 // zero would move the end anchor out from under that scroll.
118 cardCoverage.value = coverage;
119 return;
120 }
121 // Animated so a coverage change at rest (discrete max-height
122 // corrections) glides the feed instead of stepping it; toggle timing is
123 // owned by the host's progress values.
124 cardCoverage.value = withTiming(coverage, {
125 duration: USER_INPUT_TOGGLE_DURATION_MS,
126 easing: Easing.out(Easing.cubic),
127 });
128 }, [cardCoverage]);
129 const handleBarLayout = useCallback(
130 (event: LayoutChangeEvent) => {
131 barHeightRef.current = event.nativeEvent.layout.height;
132 notifyCoverage();
133 },
134 [notifyCoverage],
135 );
136 const handleCardLayout = useCallback(
137 (event: LayoutChangeEvent) => {
138 cardHeightRef.current = event.nativeEvent.layout.height;
139 cardHeight.value = event.nativeEvent.layout.height;
140 notifyCoverage();
141 },
142 [cardHeight, notifyCoverage],
143 );
144 const cardProgress = props.cardProgress;
145 // No opacity: fading an opaque card over the live transcript reads as a
146 // crossfade (card text, transcript, and bar all half-visible at once).
147 // Instead the card stays opaque and slides its full height down past the
148 // clipping window's bottom edge, so the transcript is only revealed where
149 // the card has physically left.
150 const cardAnimatedStyle = useAnimatedStyle(() => {
151 const progress = cardProgress === undefined ? 1 : cardProgress.value;
152 return {
153 transform: [{ translateY: (1 - progress) * cardHeight.value }],
154 };
155 });
156
157 // On iOS the card stays MOUNTED while collapsed (hidden via the animated
158 // style): expanding animates existing views on the UI thread the same
159 // frame the host starts the progress timing, instead of paying a React
160 // mount + layout before anything moves.
161 const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
162 const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
163 // The bar renders UNDER the card (earlier in JSX), always opaque: while
164 // expanded the opaque card covers it, and during the collapse slide the
165 // card's top edge wipes past and reveals it — no opacity handoff, so no
166 // crossfade frames.
167 const bar = showBar ? (
168 <View
169 onLayout={handleBarLayout}
170 pointerEvents={props.collapsed ? "auto" : "none"}
171 accessibilityElementsHidden={!props.collapsed}
172 importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
173 className="flex-row items-center gap-2 rounded-full border border-border bg-card-alt py-1.5 pl-4 pr-1.5"
174 >
175 <Pressable
176 accessibilityRole="button"
177 accessibilityLabel={`Expand user input, ${questionCount} question${
178 questionCount === 1 ? "" : "s"
179 }`}
180 onPress={props.onToggleCollapsed}
181 className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
182 >
183 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
184 User input needed
185 </Text>
186 <Text className="font-sans text-xs text-foreground-muted">
187 {questionCount} question{questionCount === 1 ? "" : "s"}
188 </Text>
189 <View className="flex-1" />
190 <SymbolView
191 name="chevron.up"
192 size={12}
193 tintColorClassName={"accent-icon-subtle"}
194 type="monochrome"
195 />
196 </Pressable>
197 {props.onStopThread ? (
198 <ControlPill
199 accessibilityLabel="Stop"
200 icon="stop.fill"
201 variant="danger"
202 className="h-9 w-9"
203 onPress={props.onStopThread}
204 />
205 ) : null}
206 </View>
207 ) : null;
208 const card = renderCard ? (
209 // The surface is opaque on purpose: the card floats over the thread
210 // feed with no blur behind it, so a translucent background renders
211 // the questions on top of whatever message happens to sit underneath.
212 <Animated.View
213 onLayout={handleCardLayout}
214 pointerEvents={props.collapsed ? "none" : "auto"}
215 accessibilityElementsHidden={props.collapsed}
216 importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
217 entering={
218 EXPANDED_CARD_IS_OVERLAY
219 ? undefined
220 : FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
221 }
222 exiting={
223 EXPANDED_CARD_IS_OVERLAY
224 ? undefined
225 : FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
226 }
227 layout={CARD_LAYOUT_TRANSITION}
228 className="overflow-hidden gap-2.5 rounded-[20px] border border-border bg-card-alt p-4"
229 style={
230 EXPANDED_CARD_IS_OVERLAY
231 ? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
232 : { maxHeight: props.maxHeight }
233 }
234 >
235 <Pressable
236 accessibilityRole="button"
237 accessibilityLabel="Collapse user input"
238 onPress={props.onToggleCollapsed}
239 className="flex-row items-start gap-2"
240 >
241 <View className="flex-1 gap-2.5">
242 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
243 User input needed
244 </Text>
245 <Text className="font-t3-bold text-lg text-foreground">Fill in the pending answers</Text>
246 </View>
247 <View className="h-8 w-8 items-center justify-center rounded-full bg-subtle-strong">
248 <SymbolView
249 name="chevron.down"
250 size={13}
251 tintColorClassName={"accent-icon-subtle"}
252 type="monochrome"
253 />
254 </View>
255 </Pressable>
256 <ScrollView
257 bounces={false}
258 className="min-h-0"
259 contentContainerClassName="gap-2.5 pb-1"
260 keyboardShouldPersistTaps="handled"
261 nestedScrollEnabled
262 showsVerticalScrollIndicator
263 style={{ flexShrink: 1 }}
264 >
265 {!canRespond ? (
266 <Text className="font-sans text-sm leading-5 text-adaptive-neutral-600-400">
267 The provider process for this request is no longer available. Interrupt or restart the
268 run to continue.
269 </Text>
270 ) : null}
271 {props.pendingUserInput.questions.map((question) => {
272 const draft = props.drafts[question.id];
273 return (
274 <View key={question.id} className="gap-2 pt-1">
275 <Text className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted">
276 {question.header}
277 </Text>
278 <Text className="font-sans text-base leading-snug text-foreground">
279 {question.question}
280 </Text>
281 <View className="gap-2">
282 {question.options.map((option) => {
283 const optionValue = option.value ?? option.label.trim();
284 const selected = isPendingUserInputOptionSelected(question, draft, optionValue);
285 const description =
286 option.description !== option.label ? option.description : undefined;
287 return (
288 <Pressable
289 key={optionValue}
290 accessibilityRole={question.multiSelect ? "checkbox" : "radio"}
291 accessibilityState={{ checked: selected, disabled: responseDisabled }}
292 disabled={responseDisabled}
293 className={cn(
294 "min-h-12 w-full rounded-2xl border px-3.5 py-3",
295 selected ? "border-primary bg-primary/10" : "border-border bg-input",
296 )}
297 onPress={() =>
298 props.onSelectOption(
299 props.pendingUserInput.requestId,
300 question,
301 optionValue,
302 )
303 }
304 >
305 <View className="min-w-0 flex-1 gap-0.5">
306 <Text
307 className={cn(
308 "font-t3-bold text-sm",
309 selected ? "text-foreground" : "text-foreground-secondary",
310 )}
311 >
312 {option.label}
313 </Text>
314 {description ? (
315 <Text className="font-sans text-sm leading-5 text-foreground-muted">
316 {description}
317 </Text>
318 ) : null}
319 </View>
320 </Pressable>
321 );
322 })}
323 </View>
324 {question.allowCustomAnswer !== false ? (
325 <QuestionAttachments
326 requestId={props.pendingUserInput.requestId}
327 question={question}
328 questions={props.pendingUserInput.questions}
329 disabled={responseDisabled}
330 value={draft?.customAnswer ?? ""}
331 onChangeText={(value) =>
332 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
333 }
334 onInputFocusChange={props.onInputFocusChange}
335 />
336 ) : null}
337 </View>
338 );
339 })}
340 </ScrollView>
341 <RequestActionButton
342 label="Submit answers"
343 size="large"
344 tone={props.answers ? "primary" : "secondary"}
345 disabled={responseDisabled || props.answers === null}
346 onPress={() => void props.onSubmit()}
347 />
348 {props.pendingUserInput.dismissible ? (
349 <Pressable
350 accessibilityRole="button"
351 className="items-center justify-center rounded-2xl px-4 py-2.5 active:opacity-70"
352 disabled={isResponding}
353 onPress={() => void props.onDismiss()}
354 >
355 <Text className="font-t3-bold text-sm text-foreground-muted">
356 Dismiss without answering
357 </Text>
358 </Pressable>
359 ) : null}
360 </Animated.View>
361 ) : null;
362 return (
363 <View className="relative">
364 {bar}
365 {EXPANDED_CARD_IS_OVERLAY ? (
366 // Clipping window for the collapse slide: same footprint as the
367 // expanded card, bottom edge on the bar's bottom edge. The sliding
368 // card exits through the bottom edge instead of drawing over the
369 // composer area, wiping the bar (and the transcript) into view.
370 <View
371 pointerEvents={props.collapsed ? "none" : "box-none"}
372 className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
373 style={{ height: props.maxHeight }}
374 >
375 {card}
376 </View>
377 ) : (
378 card
379 )}
380 </View>
381 );
382}