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

PendingUserInputCard.tsx

391 lines15.4 KB

1import { QuestionAttachments } from "./QuestionAttachments";
2import type { RuntimeRequestId } from "@t3tools/contracts";
3import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
4import { useCallback, useRef } from "react";
5import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
6import Animated, {
7 Easing,
8 FadeInUp,
9 FadeOutDown,
10 LinearTransition,
11 useAnimatedStyle,
12 useSharedValue,
13 withTiming,
14 type SharedValue,
15} from "react-native-reanimated";
16​
17import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
18​
19import { SymbolView } from "../../components/AppSymbol";
20import { AppText as Text } from "../../components/AppText";
21import { ControlPill } from "../../components/ControlPill";
22import { cn } from "../../lib/cn";
23import {
24 isPendingUserInputOptionSelected,
25 type PendingUserInput,
26 type PendingUserInputDraftAnswer,
27} from "../../lib/threadActivity";
28​
29export interface PendingUserInputCardProps {
30 readonly pendingUserInput: PendingUserInput;
31 /**
32 * Constant while a request is pending (it reserves keyboard space), so the
33 * keyboard transition is pure translation; changes only on rare discrete
34 * corrections, which the layout transition smooths.
35 */
36 readonly maxHeight: number;
37 readonly collapsed: boolean;
38 readonly onToggleCollapsed: () => void;
39 /** Renders a stop control on the collapsed bar, which replaces the composer. */
40 readonly onStopThread?: () => void;
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: RuntimeRequestId | null;
60 readonly onSelectOption: (
61 requestId: RuntimeRequestId,
62 question: ThreadUserInputQuestion,
63 value: string,
64 ) => void;
65 readonly onChangeCustomAnswer: (
66 requestId: RuntimeRequestId,
67 questionId: string,
68 customAnswer: string,
69 ) => void;
70 readonly onSubmit: () => Promise<unknown>;
71 /** Closes an async question without a reply. Hidden for native callback questions. */
72 readonly onDismiss: () => Promise<unknown>;
74​
75/**
76 * On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
77 * card is an absolutely-positioned overlay rising above it. The overlay's
78 * measured height (which drives the thread feed's bottom inset) therefore
79 * never changes on collapse/expand, so the transcript stays perfectly still
80 * while the card animates over it.
81 *
82 * Android cannot use the overlay: it does not hit-test touches outside a
83 * parent's bounds, which made everything above the bar-sized wrapper
84 * untouchable. There the expanded card renders in-flow instead (the wrapper
85 * grows with it, and the host skips the coverage inset since the measured
86 * overlay already includes the card).
87 */
88const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
89​
90const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
91​
92export function PendingUserInputCard(props: PendingUserInputCardProps) {
93 const questionCount = props.pendingUserInput.questions.length;
94 // Message responses start a new run and remain available after the provider exits.
95 const canRespond = props.pendingUserInput.responseCapability !== "not_resumable";
96​
97 const cardCoverage = props.cardCoverage;
98 const barHeightRef = useRef(0);
99 const cardHeightRef = useRef(0);
100 // Measured card height, written straight from onLayout: the collapse slide
101 // distance. Not animated — it only changes on discrete relayouts.
102 const cardHeight = useSharedValue(0);
103 const notifyCoverage = useCallback(() => {
104 if (!cardCoverage) {
105 return;
106 }
107 const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
108 if (coverage === cardCoverage.value) {
109 return;
110 }
111 if (cardCoverage.value === 0) {
112 // First measurement lands while the list is doing its initial
113 // end-pin (thread opened onto a pending request); animating it from
114 // zero would move the end anchor out from under that scroll.
115 cardCoverage.value = coverage;
116 return;
117 }
118 // Animated so a coverage change at rest (discrete max-height
119 // corrections) glides the feed instead of stepping it; toggle timing is
120 // owned by the host's progress values.
121 cardCoverage.value = withTiming(coverage, {
122 duration: USER_INPUT_TOGGLE_DURATION_MS,
123 easing: Easing.out(Easing.cubic),
124 });
125 }, [cardCoverage]);
126 const handleBarLayout = useCallback(
127 (event: LayoutChangeEvent) => {
128 barHeightRef.current = event.nativeEvent.layout.height;
129 notifyCoverage();
130 },
131 [notifyCoverage],
132 );
133 const handleCardLayout = useCallback(
134 (event: LayoutChangeEvent) => {
135 cardHeightRef.current = event.nativeEvent.layout.height;
136 cardHeight.value = event.nativeEvent.layout.height;
137 notifyCoverage();
138 },
139 [cardHeight, notifyCoverage],
140 );
141 const cardProgress = props.cardProgress;
142 // No opacity: fading an opaque card over the live transcript reads as a
143 // crossfade (card text, transcript, and bar all half-visible at once).
144 // Instead the card stays opaque and slides its full height down past the
145 // clipping window's bottom edge, so the transcript is only revealed where
146 // the card has physically left.
147 const cardAnimatedStyle = useAnimatedStyle(() => {
148 const progress = cardProgress === undefined ? 1 : cardProgress.value;
149 return {
150 transform: [{ translateY: (1 - progress) * cardHeight.value }],
151 };
152 });
153​
154 // On iOS the card stays MOUNTED while collapsed (hidden via the animated
155 // style): expanding animates existing views on the UI thread the same
156 // frame the host starts the progress timing, instead of paying a React
157 // mount + layout before anything moves.
158 const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
159 const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
160 // The bar renders UNDER the card (earlier in JSX), always opaque: while
161 // expanded the opaque card covers it, and during the collapse slide the
162 // card's top edge wipes past and reveals it — no opacity handoff, so no
163 // crossfade frames.
164 const bar = showBar ? (
165 <View
166 onLayout={handleBarLayout}
167 pointerEvents={props.collapsed ? "auto" : "none"}
168 accessibilityElementsHidden={!props.collapsed}
169 importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
170 className="flex-row items-center gap-2 rounded-full border border-border bg-card-alt py-1.5 pl-4 pr-1.5"
171 >
172 <Pressable
173 accessibilityRole="button"
174 accessibilityLabel={`Expand user input, ${questionCount} question${
175 questionCount === 1 ? "" : "s"
176 }`}
177 onPress={props.onToggleCollapsed}
178 className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
179 >
180 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
181 User input needed
182 </Text>
183 <Text className="font-sans text-xs text-foreground-muted">
184 {questionCount} question{questionCount === 1 ? "" : "s"}
185 </Text>
186 <View className="flex-1" />
187 <SymbolView
188 name="chevron.up"
189 size={12}
190 tintColorClassName={"accent-icon-subtle"}
191 type="monochrome"
192 />
193 </Pressable>
194 {props.onStopThread ? (
195 <ControlPill
196 accessibilityLabel="Stop"
197 icon="stop.fill"
198 variant="danger"
199 className="h-9 w-9"
200 onPress={props.onStopThread}
201 />
202 ) : null}
203 </View>
204 ) : null;
205 const card = renderCard ? (
206 // The surface is opaque on purpose: the card floats over the thread
207 // feed with no blur behind it, so a translucent background renders
208 // the questions on top of whatever message happens to sit underneath.
209 <Animated.View
210 onLayout={handleCardLayout}
211 pointerEvents={props.collapsed ? "none" : "auto"}
212 accessibilityElementsHidden={props.collapsed}
213 importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
214 entering={
215 EXPANDED_CARD_IS_OVERLAY
216 ? undefined
217 : FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
218 }
219 exiting={
220 EXPANDED_CARD_IS_OVERLAY
221 ? undefined
222 : FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
223 }
224 layout={CARD_LAYOUT_TRANSITION}
225 className="overflow-hidden gap-2.5 rounded-[20px] border border-border bg-card-alt p-4"
226 style={
227 EXPANDED_CARD_IS_OVERLAY
228 ? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
229 : { maxHeight: props.maxHeight }
230 }
231 >
232 <Pressable
233 accessibilityRole="button"
234 accessibilityLabel="Collapse user input"
235 onPress={props.onToggleCollapsed}
236 className="flex-row items-start gap-2"
237 >
238 <View className="flex-1 gap-2.5">
239 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
240 User input needed
241 </Text>
242 <Text className="font-t3-bold text-lg text-foreground">Fill in the pending answers</Text>
243 </View>
244 <View className="h-8 w-8 items-center justify-center rounded-full bg-subtle-strong">
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-foreground-muted">
273 {question.header}
274 </Text>
275 <Text className="font-sans text-base leading-snug text-foreground">
276 {question.question}
277 </Text>
278 <View className="gap-2">
279 {question.options.map((option) => {
280 const optionValue = option.value ?? option.label.trim();
281 const selected = isPendingUserInputOptionSelected(question, draft, optionValue);
282 const description =
283 option.description !== option.label ? option.description : undefined;
284 return (
285 <Pressable
286 key={optionValue}
287 disabled={!canRespond}
288 className={cn(
289 "min-h-12 w-full rounded-2xl border px-3.5 py-3",
290 selected ? "border-primary bg-primary/10" : "border-border bg-input",
291 )}
292 onPress={() =>
293 props.onSelectOption(
294 props.pendingUserInput.requestId,
295 question,
296 optionValue,
297 )
298 }
299 >
300 <View className="min-w-0 flex-1 gap-0.5">
301 <Text
302 className={cn(
303 "font-t3-bold text-sm",
304 selected ? "text-foreground" : "text-foreground-secondary",
305 )}
306 >
307 {option.label}
308 </Text>
309 {description ? (
310 <Text className="font-sans text-sm leading-5 text-foreground-muted">
311 {description}
312 </Text>
313 ) : null}
314 </View>
315 </Pressable>
316 );
317 })}
318 </View>
319 {question.allowCustomAnswer !== false ? (
320 <QuestionAttachments
321 requestId={props.pendingUserInput.requestId}
322 question={question}
323 questions={props.pendingUserInput.questions}
324 disabled={!canRespond}
325 value={draft?.customAnswer ?? ""}
326 onChangeText={(value) =>
327 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
328 }
329 onInputFocusChange={props.onInputFocusChange}
330 />
331 ) : null}
332 </View>
333 );
334 })}
335 </ScrollView>
336 <Pressable
337 className={cn(
338 "items-center justify-center rounded-2xl px-4 py-3.5",
339 props.answers ? "bg-primary" : "bg-subtle-strong",
340 )}
341 disabled={
342 !canRespond ||
343 props.answers === null ||
344 props.respondingUserInputId === props.pendingUserInput.requestId
345 }
346 onPress={() => void props.onSubmit()}
347 >
348 <Text
349 className={cn(
350 "font-t3-extrabold text-sm",
351 props.answers ? "text-primary-foreground" : "text-foreground-muted",
352 )}
353 >
354 Submit answers
355 </Text>
356 </Pressable>
357 {props.pendingUserInput.dismissible ? (
358 <Pressable
359 accessibilityRole="button"
360 className="items-center justify-center rounded-2xl px-4 py-2.5 active:opacity-70"
361 disabled={props.respondingUserInputId === props.pendingUserInput.requestId}
362 onPress={() => void props.onDismiss()}
363 >
364 <Text className="font-t3-bold text-sm text-foreground-muted">
365 Dismiss without answering
366 </Text>
367 </Pressable>
368 ) : null}
369 </Animated.View>
370 ) : null;
371 return (
372 <View className="relative">
373 {bar}
374 {EXPANDED_CARD_IS_OVERLAY ? (
375 // Clipping window for the collapse slide: same footprint as the
376 // expanded card, bottom edge on the bar's bottom edge. The sliding
377 // card exits through the bottom edge instead of drawing over the
378 // composer area, wiping the bar (and the transcript) into view.
379 <View
380 pointerEvents={props.collapsed ? "none" : "box-none"}
381 className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
382 style={{ height: props.maxHeight }}
383 >
384 {card}
385 </View>
386 ) : (
387 card
388 )}
389 </View>
390 );