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

PendingUserInputCard.tsx

389 lines15.6 KB

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