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

PendingUserInputCard.tsx

368 lines14.5 KB

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