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 { useThemeColor } from "../../lib/useThemeColor";
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: ApprovalRequestId | null;
59 readonly onSelectOption: (
60 requestId: ApprovalRequestId,
61 question: UserInputQuestion,
62 label: string,
63 ) => void;
64 readonly onChangeCustomAnswer: (
65 requestId: ApprovalRequestId,
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 iconSubtle = useThemeColor("--color-icon-subtle");
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-neutral-200 bg-neutral-100 py-1.5 pl-4 pr-1.5 dark:border-white/6 dark:bg-neutral-900"
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-sky-700 dark:text-sky-300">
177 User input needed
178 </Text>
179 <Text className="font-sans text-xs text-neutral-500 dark:text-neutral-400">
180 {questionCount} question{questionCount === 1 ? "" : "s"}
181 </Text>
182 <View className="flex-1" />
183 <SymbolView name="chevron.up" size={12} tintColor={iconSubtle} type="monochrome" />
184 </Pressable>
185 {props.onStopThread ? (
186 <ControlPill
187 accessibilityLabel="Stop"
188 icon="stop.fill"
189 variant="danger"
190 className="h-9 w-9"
191 onPress={props.onStopThread}
192 />
193 ) : null}
194 </View>
195 ) : null;
196 const card = renderCard ? (
197 // The surface is opaque on purpose: the card floats over the thread
198 // feed with no blur behind it, so a translucent background renders
199 // the questions on top of whatever message happens to sit underneath.
200 <Animated.View
201 onLayout={handleCardLayout}
202 pointerEvents={props.collapsed ? "none" : "auto"}
203 accessibilityElementsHidden={props.collapsed}
204 importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
205 entering={
206 EXPANDED_CARD_IS_OVERLAY
207 ? undefined
208 : FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
209 }
210 exiting={
211 EXPANDED_CARD_IS_OVERLAY
212 ? undefined
213 : FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
214 }
215 layout={CARD_LAYOUT_TRANSITION}
216 className="overflow-hidden gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900"
217 style={
218 EXPANDED_CARD_IS_OVERLAY
219 ? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
220 : { maxHeight: props.maxHeight }
221 }
222 >
223 <Pressable
224 accessibilityRole="button"
225 accessibilityLabel="Collapse user input"
226 onPress={props.onToggleCollapsed}
227 className="flex-row items-start gap-2"
228 >
229 <View className="flex-1 gap-2.5">
230 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
231 User input needed
232 </Text>
233 <Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
234 Fill in the pending answers
235 </Text>
236 </View>
237 <View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/8">
238 <SymbolView name="chevron.down" size={13} tintColor={iconSubtle} type="monochrome" />
239 </View>
240 </Pressable>
241 <ScrollView
242 bounces={false}
243 className="min-h-0"
244 contentContainerClassName="gap-2.5 pb-1"
245 keyboardShouldPersistTaps="handled"
246 nestedScrollEnabled
247 showsVerticalScrollIndicator
248 style={{ flexShrink: 1 }}
249 >
250 {props.pendingUserInput.questions.map((question) => {
251 const draft = props.drafts[question.id];
252 return (
253 <View key={question.id} className="gap-2 pt-1">
254 <Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
255 {question.header}
256 </Text>
257 <Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
258 {question.question}
259 </Text>
260 <View className="gap-2">
261 {question.options.map((option) => {
262 const selected = isPendingUserInputOptionSelected(draft, option.label);
263 const description =
264 option.description !== option.label ? option.description : undefined;
265 return (
266 <Pressable
267 key={option.label}
268 className={cn(
269 "min-h-12 w-full rounded-2xl border px-3.5 py-3",
270 selected
271 ? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
272 : "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
273 )}
274 onPress={() =>
275 props.onSelectOption(
276 props.pendingUserInput.requestId,
277 question,
278 option.label,
279 )
280 }
281 >
282 <View className="min-w-0 flex-1 gap-0.5">
283 <Text
284 className={cn(
285 "font-t3-bold text-sm",
286 selected
287 ? "text-sky-700 dark:text-sky-300"
288 : "text-neutral-700 dark:text-neutral-200",
289 )}
290 >
291 {option.label}
292 </Text>
293 {description ? (
294 <Text className="font-sans text-sm leading-5 text-neutral-500 dark:text-neutral-400">
295 {description}
296 </Text>
297 ) : null}
298 </View>
299 </Pressable>
300 );
301 })}
302 </View>
303 <TextInput
304 value={draft?.customAnswer ?? ""}
305 onChangeText={(value) =>
306 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
307 }
308 onFocus={() => props.onInputFocusChange?.(true)}
309 onBlur={() => props.onInputFocusChange?.(false)}
310 placeholder="Or type a custom answer"
311 className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
312 />
313 </View>
314 );
315 })}
316 </ScrollView>
317 <Pressable
318 className={cn(
319 "items-center justify-center rounded-2xl px-4 py-3.5",
320 props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
321 )}
322 disabled={
323 props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
324 }
325 onPress={() => void props.onSubmit()}
326 >
327 <Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
328 </Pressable>
329 </Animated.View>
330 ) : null;
331 return (
332 <View className="relative">
333 {bar}
334 {EXPANDED_CARD_IS_OVERLAY ? (
335 // Clipping window for the collapse slide: same footprint as the
336 // expanded card, bottom edge on the bar's bottom edge. The sliding
337 // card exits through the bottom edge instead of drawing over the
338 // composer area, wiping the bar (and the transcript) into view.
339 <View
340 pointerEvents={props.collapsed ? "none" : "box-none"}
341 className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
342 style={{ height: props.maxHeight }}
343 >
344 {card}
345 </View>
346 ) : (
347 card
348 )}
349 </View>
350 );
351}