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