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