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

PendingUserInputCard.tsx

362 lines14.5 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-adaptive-neutral-200-white-a6 bg-adaptive-neutral-100-900 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-adaptive-sky-700-300">
175 User input needed
176 </Text>
177 <Text className="font-sans text-xs text-adaptive-neutral-500-400">
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-adaptive-neutral-200-white-a6 bg-adaptive-neutral-100-900 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-adaptive-sky-700-300">
234 User input needed
235 </Text>
236 <Text className="font-t3-bold text-lg text-adaptive-neutral-950-50">
237 Fill in the pending answers
238 </Text>
239 </View>
240 <View className="h-8 w-8 items-center justify-center rounded-full bg-adaptive-neutral-200-a70-white-a8">
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-neutral-500">
263 {question.header}
264 </Text>
265 <Text className="font-sans text-base leading-snug text-adaptive-neutral-950-50">
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
280 ? "border-adaptive-blue-300-a50-blue-400-a28 bg-adaptive-blue-50-blue-400-a14"
281 : "border-adaptive-neutral-200-white-a6 bg-adaptive-white-neutral-950-a70",
282 )}
283 onPress={() =>
284 props.onSelectOption(
285 props.pendingUserInput.requestId,
286 question,
287 optionValue,
288 )
289 }
290 >
291 <View className="min-w-0 flex-1 gap-0.5">
292 <Text
293 className={cn(
294 "font-t3-bold text-sm",
295 selected
296 ? "text-adaptive-sky-700-300"
297 : "text-adaptive-neutral-600-300",
298 )}
299 >
300 {option.label}
301 </Text>
302 {description ? (
303 <Text className="font-sans text-sm leading-5 text-adaptive-neutral-500-400">
304 {description}
305 </Text>
306 ) : null}
307 </View>
308 </Pressable>
309 );
310 })}
311 </View>
312 {question.allowCustomAnswer !== false ? (
313 <TextInput
314 value={draft?.customAnswer ?? ""}
315 onChangeText={(value) =>
316 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
317 }
318 onFocus={() => props.onInputFocusChange?.(true)}
319 onBlur={() => props.onInputFocusChange?.(false)}
320 placeholder="Or type a custom answer"
321 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"
322 />
323 ) : null}
324 </View>
325 );
326 })}
327 </ScrollView>
328 <Pressable
329 className={cn(
330 "items-center justify-center rounded-2xl px-4 py-3.5",
331 props.answers ? "bg-blue-500" : "bg-adaptive-neutral-200-700-a60",
332 )}
333 disabled={
334 props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
335 }
336 onPress={() => void props.onSubmit()}
337 >
338 <Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
339 </Pressable>
340 </Animated.View>
341 ) : null;
342 return (
343 <View className="relative">
344 {bar}
345 {EXPANDED_CARD_IS_OVERLAY ? (
346 // Clipping window for the collapse slide: same footprint as the
347 // expanded card, bottom edge on the bar's bottom edge. The sliding
348 // card exits through the bottom edge instead of drawing over the
349 // composer area, wiping the bar (and the transcript) into view.
350 <View
351 pointerEvents={props.collapsed ? "none" : "box-none"}
352 className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
353 style={{ height: props.maxHeight }}
354 >
355 {card}
356 </View>
357 ) : (
358 card
359 )}
360 </View>
361 );