Open History to see the last commit
1import { QuestionAttachments } from "./QuestionAttachments";
2import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
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 } 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: ApprovalRequestId | null;
59 readonly onSelectOption: (
60 requestId: ApprovalRequestId,
61 question: UserInputQuestion,
62 value: string,
63 ) => void;
64 readonly onChangeCustomAnswer: (
65 requestId: ApprovalRequestId,
66 questionId: string,
67 customAnswer: string,
68 ) => void;
69 readonly onSubmit: () => Promise<unknown>;
70 /** Closes an async question without a reply. Hidden for native callback questions. */
71 readonly onDismiss: () => Promise<unknown>;
72}
73
74/**
75 * On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
76 * card is an absolutely-positioned overlay rising above it. The overlay's
77 * measured height (which drives the thread feed's bottom inset) therefore
78 * never changes on collapse/expand, so the transcript stays perfectly still
79 * while the card animates over it.
80 *
81 * Android cannot use the overlay: it does not hit-test touches outside a
82 * parent's bounds, which made everything above the bar-sized wrapper
83 * untouchable. There the expanded card renders in-flow instead (the wrapper
84 * grows with it, and the host skips the coverage inset since the measured
85 * overlay already includes the card).
86 */
87const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
88
89const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
90
91export function PendingUserInputCard(props: PendingUserInputCardProps) {
92 const questionCount = props.pendingUserInput.questions.length;
93
94 const cardCoverage = props.cardCoverage;
95 const barHeightRef = useRef(0);
96 const cardHeightRef = useRef(0);
97 // Measured card height, written straight from onLayout: the collapse slide
98 // distance. Not animated — it only changes on discrete relayouts.
99 const cardHeight = useSharedValue(0);
100 const notifyCoverage = useCallback(() => {
101 if (!cardCoverage) {
102 return;
103 }
104 const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
105 if (coverage === cardCoverage.value) {
106 return;
107 }
108 if (cardCoverage.value === 0) {
109 // First measurement lands while the list is doing its initial
110 // end-pin (thread opened onto a pending request); animating it from
111 // zero would move the end anchor out from under that scroll.
112 cardCoverage.value = coverage;
113 return;
114 }
115 // Animated so a coverage change at rest (discrete max-height
116 // corrections) glides the feed instead of stepping it; toggle timing is
117 // owned by the host's progress values.
118 cardCoverage.value = withTiming(coverage, {
119 duration: USER_INPUT_TOGGLE_DURATION_MS,
120 easing: Easing.out(Easing.cubic),
121 });
122 }, [cardCoverage]);
123 const handleBarLayout = useCallback(
124 (event: LayoutChangeEvent) => {
125 barHeightRef.current = event.nativeEvent.layout.height;
126 notifyCoverage();
127 },
128 [notifyCoverage],
129 );
130 const handleCardLayout = useCallback(
131 (event: LayoutChangeEvent) => {
132 cardHeightRef.current = event.nativeEvent.layout.height;
133 cardHeight.value = event.nativeEvent.layout.height;
134 notifyCoverage();
135 },
136 [cardHeight, notifyCoverage],
137 );
138 const cardProgress = props.cardProgress;
139 // No opacity: fading an opaque card over the live transcript reads as a
140 // crossfade (card text, transcript, and bar all half-visible at once).
141 // Instead the card stays opaque and slides its full height down past the
142 // clipping window's bottom edge, so the transcript is only revealed where
143 // the card has physically left.
144 const cardAnimatedStyle = useAnimatedStyle(() => {
145 const progress = cardProgress === undefined ? 1 : cardProgress.value;
146 return {
147 transform: [{ translateY: (1 - progress) * cardHeight.value }],
148 };
149 });
150
151 // On iOS the card stays MOUNTED while collapsed (hidden via the animated
152 // style): expanding animates existing views on the UI thread the same
153 // frame the host starts the progress timing, instead of paying a React
154 // mount + layout before anything moves.
155 const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
156 const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
157 // The bar renders UNDER the card (earlier in JSX), always opaque: while
158 // expanded the opaque card covers it, and during the collapse slide the
159 // card's top edge wipes past and reveals it — no opacity handoff, so no
160 // crossfade frames.
161 const bar = showBar ? (
162 <View
163 onLayout={handleBarLayout}
164 pointerEvents={props.collapsed ? "auto" : "none"}
165 accessibilityElementsHidden={!props.collapsed}
166 importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
167 className="flex-row items-center gap-2 rounded-full border border-border bg-card-alt py-1.5 pl-4 pr-1.5"
168 >
169 <Pressable
170 accessibilityRole="button"
171 accessibilityLabel={`Expand user input, ${questionCount} question${
172 questionCount === 1 ? "" : "s"
173 }`}
174 onPress={props.onToggleCollapsed}
175 className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
176 >
177 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
178 User input needed
179 </Text>
180 <Text className="font-sans text-xs text-foreground-muted">
181 {questionCount} question{questionCount === 1 ? "" : "s"}
182 </Text>
183 <View className="flex-1" />
184 <SymbolView
185 name="chevron.up"
186 size={12}
187 tintColorClassName={"accent-icon-subtle"}
188 type="monochrome"
189 />
190 </Pressable>
191 {props.onStopThread ? (
192 <ControlPill
193 accessibilityLabel="Stop"
194 icon="stop.fill"
195 variant="danger"
196 className="h-9 w-9"
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-border bg-card-alt 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-foreground-secondary">
237 User input needed
238 </Text>
239 <Text className="font-t3-bold text-lg text-foreground">Fill in the pending answers</Text>
240 </View>
241 <View className="h-8 w-8 items-center justify-center rounded-full bg-subtle-strong">
242 <SymbolView
243 name="chevron.down"
244 size={13}
245 tintColorClassName={"accent-icon-subtle"}
246 type="monochrome"
247 />
248 </View>
249 </Pressable>
250 <ScrollView
251 bounces={false}
252 className="min-h-0"
253 contentContainerClassName="gap-2.5 pb-1"
254 keyboardShouldPersistTaps="handled"
255 nestedScrollEnabled
256 showsVerticalScrollIndicator
257 style={{ flexShrink: 1 }}
258 >
259 {props.pendingUserInput.questions.map((question) => {
260 const draft = props.drafts[question.id];
261 return (
262 <View key={question.id} className="gap-2 pt-1">
263 <Text className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted">
264 {question.header}
265 </Text>
266 <Text className="font-sans text-base leading-snug text-foreground">
267 {question.question}
268 </Text>
269 <View className="gap-2">
270 {question.options.map((option) => {
271 const optionValue = option.value ?? option.label.trim();
272 const selected = isPendingUserInputOptionSelected(question, draft, optionValue);
273 const description =
274 option.description !== option.label ? option.description : undefined;
275 return (
276 <Pressable
277 key={optionValue}
278 className={cn(
279 "min-h-12 w-full rounded-2xl border px-3.5 py-3",
280 selected ? "border-primary bg-primary/10" : "border-border bg-input",
281 )}
282 onPress={() =>
283 props.onSelectOption(
284 props.pendingUserInput.requestId,
285 question,
286 optionValue,
287 )
288 }
289 >
290 <View className="min-w-0 flex-1 gap-0.5">
291 <Text
292 className={cn(
293 "font-t3-bold text-sm",
294 selected ? "text-foreground" : "text-foreground-secondary",
295 )}
296 >
297 {option.label}
298 </Text>
299 {description ? (
300 <Text className="font-sans text-sm leading-5 text-foreground-muted">
301 {description}
302 </Text>
303 ) : null}
304 </View>
305 </Pressable>
306 );
307 })}
308 </View>
309 <QuestionAttachments
310 requestId={props.pendingUserInput.requestId}
311 question={question}
312 questions={props.pendingUserInput.questions}
313 disabled={props.respondingUserInputId === props.pendingUserInput.requestId}
314 value={draft?.customAnswer ?? ""}
315 onChangeText={(value) =>
316 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
317 }
318 onInputFocusChange={props.onInputFocusChange}
319 />
320 </View>
321 );
322 })}
323 </ScrollView>
324 <Pressable
325 className={cn(
326 "items-center justify-center rounded-2xl px-4 py-3.5",
327 props.answers ? "bg-primary" : "bg-subtle-strong",
328 )}
329 disabled={
330 props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
331 }
332 onPress={() => void props.onSubmit()}
333 >
334 <Text
335 className={cn(
336 "font-t3-extrabold text-sm",
337 props.answers ? "text-primary-foreground" : "text-foreground-muted",
338 )}
339 >
340 Submit answers
341 </Text>
342 </Pressable>
343 {props.pendingUserInput.dismissible ? (
344 <Pressable
345 accessibilityRole="button"
346 className="items-center justify-center rounded-2xl px-4 py-2.5 active:opacity-70"
347 disabled={props.respondingUserInputId === props.pendingUserInput.requestId}
348 onPress={() => void props.onDismiss()}
349 >
350 <Text className="font-t3-bold text-sm text-foreground-muted">
351 Dismiss without answering
352 </Text>
353 </Pressable>
354 ) : null}
355 </Animated.View>
356 ) : null;
357 return (
358 <View className="relative">
359 {bar}
360 {EXPANDED_CARD_IS_OVERLAY ? (
361 // Clipping window for the collapse slide: same footprint as the
362 // expanded card, bottom edge on the bar's bottom edge. The sliding
363 // card exits through the bottom edge instead of drawing over the
364 // composer area, wiping the bar (and the transcript) into view.
365 <View
366 pointerEvents={props.collapsed ? "none" : "box-none"}
367 className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
368 style={{ height: props.maxHeight }}
369 >
370 {card}
371 </View>
372 ) : (
373 card
374 )}
375 </View>
376 );
377}