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

PendingUserInputCard.tsx

377 lines14.8 KB

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 {
22 isPendingUserInputOptionSelected,
23 type PendingUserInput,
24 type PendingUserInputDraftAnswer,
25} from "../../lib/threadActivity";
26​
27export interface PendingUserInputCardProps {
28 readonly pendingUserInput: PendingUserInput;
29 /**
30 * Constant while a request is pending (it reserves keyboard space), so the
31 * keyboard transition is pure translation; changes only on rare discrete
32 * corrections, which the layout transition smooths.
33 */
34 readonly maxHeight: number;
35 readonly collapsed: boolean;
36 readonly onToggleCollapsed: () => void;
37 /** Renders a stop control on the collapsed bar, which replaces the composer. */
38 readonly onStopThread?: () => void;
39 /**
40 * 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the
41 * collapsed bar (inside a clipping window) on the UI thread; the host
42 * animates it directly from the tap handler so the card and the feed
43 * inset glide start the same frame.
44 */
45 readonly cardProgress?: SharedValue<number>;
46 /**
47 * Receives how far the expanded card extends above the bar footprint
48 * (written from onLayout with no re-render); the host adds it to the
49 * thread feed's end inset so the end of the chat stays visible above the
50 * card.
51 */
52 readonly cardCoverage?: SharedValue<number>;
53 /** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */
54 readonly onInputFocusChange?: (focused: boolean) => void;
55 readonly drafts: Record<string, PendingUserInputDraftAnswer>;
56 readonly answers: Record<string, string | ReadonlyArray<string>> | null;
57 readonly respondingUserInputId: ApprovalRequestId | null;
58 readonly onSelectOption: (
59 requestId: ApprovalRequestId,
60 question: UserInputQuestion,
61 value: string,
62 ) => void;
63 readonly onChangeCustomAnswer: (
64 requestId: ApprovalRequestId,
65 questionId: string,
66 customAnswer: string,
67 ) => void;
68 readonly onSubmit: () => Promise<unknown>;
69 /** Closes an async question without a reply. Hidden for native callback questions. */
70 readonly onDismiss: () => Promise<unknown>;
72​
73/**
74 * On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
75 * card is an absolutely-positioned overlay rising above it. The overlay's
76 * measured height (which drives the thread feed's bottom inset) therefore
77 * never changes on collapse/expand, so the transcript stays perfectly still
78 * while the card animates over it.
79 *
80 * Android cannot use the overlay: it does not hit-test touches outside a
81 * parent's bounds, which made everything above the bar-sized wrapper
82 * untouchable. There the expanded card renders in-flow instead (the wrapper
83 * grows with it, and the host skips the coverage inset since the measured
84 * overlay already includes the card).
85 */
86const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
87​
88const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
89​
90export function PendingUserInputCard(props: PendingUserInputCardProps) {
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-border bg-card-alt py-1.5 pl-4 pr-1.5"
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-foreground-secondary">
177 User input needed
178 </Text>
179 <Text className="font-sans text-xs text-foreground-muted">
180 {questionCount} question{questionCount === 1 ? "" : "s"}
181 </Text>
182 <View className="flex-1" />
183 <SymbolView
184 name="chevron.up"
185 size={12}
186 tintColorClassName={"accent-icon-subtle"}
187 type="monochrome"
188 />
189 </Pressable>
190 {props.onStopThread ? (
191 <ControlPill
192 accessibilityLabel="Stop"
193 icon="stop.fill"
194 variant="danger"
195 className="h-9 w-9"
196 onPress={props.onStopThread}
197 />
198 ) : null}
199 </View>
200 ) : null;
201 const card = renderCard ? (
202 // The surface is opaque on purpose: the card floats over the thread
203 // feed with no blur behind it, so a translucent background renders
204 // the questions on top of whatever message happens to sit underneath.
205 <Animated.View
206 onLayout={handleCardLayout}
207 pointerEvents={props.collapsed ? "none" : "auto"}
208 accessibilityElementsHidden={props.collapsed}
209 importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
210 entering={
211 EXPANDED_CARD_IS_OVERLAY
212 ? undefined
213 : FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
214 }
215 exiting={
216 EXPANDED_CARD_IS_OVERLAY
217 ? undefined
218 : FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
219 }
220 layout={CARD_LAYOUT_TRANSITION}
221 className="overflow-hidden gap-2.5 rounded-[20px] border border-border bg-card-alt p-4"
222 style={
223 EXPANDED_CARD_IS_OVERLAY
224 ? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
225 : { maxHeight: props.maxHeight }
226 }
227 >
228 <Pressable
229 accessibilityRole="button"
230 accessibilityLabel="Collapse user input"
231 onPress={props.onToggleCollapsed}
232 className="flex-row items-start gap-2"
233 >
234 <View className="flex-1 gap-2.5">
235 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
236 User input needed
237 </Text>
238 <Text className="font-t3-bold text-lg text-foreground">Fill in the pending answers</Text>
239 </View>
240 <View className="h-8 w-8 items-center justify-center rounded-full bg-subtle-strong">
241 <SymbolView
242 name="chevron.down"
243 size={13}
244 tintColorClassName={"accent-icon-subtle"}
245 type="monochrome"
246 />
247 </View>
248 </Pressable>
249 <ScrollView
250 bounces={false}
251 className="min-h-0"
252 contentContainerClassName="gap-2.5 pb-1"
253 keyboardShouldPersistTaps="handled"
254 nestedScrollEnabled
255 showsVerticalScrollIndicator
256 style={{ flexShrink: 1 }}
257 >
258 {props.pendingUserInput.questions.map((question) => {
259 const draft = props.drafts[question.id];
260 return (
261 <View key={question.id} className="gap-2 pt-1">
262 <Text className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted">
263 {question.header}
264 </Text>
265 <Text className="font-sans text-base leading-snug text-foreground">
266 {question.question}
267 </Text>
268 <View className="gap-2">
269 {question.options.map((option) => {
270 const optionValue = option.value ?? option.label.trim();
271 const selected = isPendingUserInputOptionSelected(question, draft, optionValue);
272 const description =
273 option.description !== option.label ? option.description : undefined;
274 return (
275 <Pressable
276 key={optionValue}
277 className={cn(
278 "min-h-12 w-full rounded-2xl border px-3.5 py-3",
279 selected ? "border-primary bg-primary/10" : "border-border bg-input",
280 )}
281 onPress={() =>
282 props.onSelectOption(
283 props.pendingUserInput.requestId,
284 question,
285 optionValue,
286 )
287 }
288 >
289 <View className="min-w-0 flex-1 gap-0.5">
290 <Text
291 className={cn(
292 "font-t3-bold text-sm",
293 selected ? "text-foreground" : "text-foreground-secondary",
294 )}
295 >
296 {option.label}
297 </Text>
298 {description ? (
299 <Text className="font-sans text-sm leading-5 text-foreground-muted">
300 {description}
301 </Text>
302 ) : null}
303 </View>
304 </Pressable>
305 );
306 })}
307 </View>
308 {question.allowCustomAnswer !== false ? (
309 <TextInput
310 value={draft?.customAnswer ?? ""}
311 onChangeText={(value) =>
312 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
313 }
314 onFocus={() => props.onInputFocusChange?.(true)}
315 onBlur={() => props.onInputFocusChange?.(false)}
316 placeholder="Or type a custom answer"
317 className="min-h-[54px] rounded-2xl border border-input-border bg-input px-3.5 py-3 font-sans text-base text-foreground"
318 />
319 ) : null}
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 );