Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PendingUserInputCard.tsx

375 lines15.1 KB

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 value: string,
63 ) => void;
64 readonly onChangeCustomAnswer: (
65 requestId: RuntimeRequestId,
66 questionId: string,
67 customAnswer: string,
68 ) => void;
69 readonly onSubmit: () => Promise<unknown>;
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 // Message responses start a new run and remain available after the provider exits.
92 const canRespond = props.pendingUserInput.responseCapability !== "not_resumable";
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-adaptive-neutral-200-white-a6 bg-adaptive-neutral-100-900 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-adaptive-sky-700-300">
178 User input needed
179 </Text>
180 <Text className="font-sans text-xs text-adaptive-neutral-500-400">
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-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 {!canRespond ? (
262 <Text className="font-sans text-sm leading-5 text-adaptive-neutral-600-400">
263 The provider process for this request is no longer available. Interrupt or restart the
264 run to continue.
265 </Text>
266 ) : null}
267 {props.pendingUserInput.questions.map((question) => {
268 const draft = props.drafts[question.id];
269 return (
270 <View key={question.id} className="gap-2 pt-1">
271 <Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500">
272 {question.header}
273 </Text>
274 <Text className="font-sans text-base leading-snug text-adaptive-neutral-950-50">
275 {question.question}
276 </Text>
277 <View className="gap-2">
278 {question.options.map((option) => {
279 const optionValue = option.value ?? option.label.trim();
280 const selected = isPendingUserInputOptionSelected(question, draft, optionValue);
281 const description =
282 option.description !== option.label ? option.description : undefined;
283 return (
284 <Pressable
285 key={optionValue}
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 optionValue,
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 {question.allowCustomAnswer !== false ? (
323 <TextInput
324 editable={canRespond}
325 value={draft?.customAnswer ?? ""}
326 onChangeText={(value) =>
327 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
328 }
329 onFocus={() => props.onInputFocusChange?.(true)}
330 onBlur={() => props.onInputFocusChange?.(false)}
331 placeholder="Or type a custom answer"
332 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"
333 />
334 ) : null}
335 </View>
336 );
337 })}
338 </ScrollView>
339 <Pressable
340 className={cn(
341 "items-center justify-center rounded-2xl px-4 py-3.5",
342 props.answers ? "bg-blue-500" : "bg-adaptive-neutral-200-700-a60",
343 )}
344 disabled={
345 !canRespond ||
346 props.answers === null ||
347 props.respondingUserInputId === props.pendingUserInput.requestId
348 }
349 onPress={() => void props.onSubmit()}
350 >
351 <Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
352 </Pressable>
353 </Animated.View>
354 ) : null;
355 return (
356 <View className="relative">
357 {bar}
358 {EXPANDED_CARD_IS_OVERLAY ? (
359 // Clipping window for the collapse slide: same footprint as the
360 // expanded card, bottom edge on the bar's bottom edge. The sliding
361 // card exits through the bottom edge instead of drawing over the
362 // composer area, wiping the bar (and the transcript) into view.
363 <View
364 pointerEvents={props.collapsed ? "none" : "box-none"}
365 className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
366 style={{ height: props.maxHeight }}
367 >
368 {card}
369 </View>
370 ) : (
371 card
372 )}
373 </View>
374 );