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

PendingUserInputCard.tsx

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