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

PendingUserInputCard.tsx

349 lines12.9 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/ui/AppSymbol";
21import { AppText as Text } from "../../components/ui/AppText";
22import { ControlPill } from "../../components/ui/ControlPill";
23import { cn } from "../../lib/cn";
24import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
25import { useOpenPullRequest } from "../../native/useOpenPullRequest";
26import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";
27import {
28 isPendingUserInputOptionSelected,
29 type PendingUserInput,
30 type PendingUserInputDraftAnswer,
31} from "../../lib/threadActivity";
32​
33export interface PendingUserInputCardProps {
34 readonly canOperateThread: boolean;
35 readonly pendingUserInput: PendingUserInput;
36 readonly maxHeight: number;
37 readonly collapsed: boolean;
38 readonly onToggleCollapsed: () => void;
39 readonly onStopThread?: () => void;
40 readonly cardProgress?: SharedValue<number>;
41 readonly cardCoverage?: SharedValue<number>;
42 readonly onInputFocusChange?: (focused: boolean) => void;
43 readonly drafts: Record<string, PendingUserInputDraftAnswer>;
44 readonly answers: Record<string, string | ReadonlyArray<string>> | null;
45 readonly respondingUserInputId: RuntimeRequestId | null;
46 readonly onSelectOption: (
47 requestId: RuntimeRequestId,
48 question: ThreadUserInputQuestion,
49 value: string,
50 ) => void;
51 readonly onChangeCustomAnswer: (
52 requestId: RuntimeRequestId,
53 questionId: string,
54 customAnswer: string,
55 ) => void;
56 readonly onSubmit: () => Promise<unknown>;
57 readonly onDismiss: () => Promise<unknown>;
59​
60/**
61 * Android cannot use the overlay: it does not hit-test touches outside a
62 * parent's bounds, which made everything above the bar-sized wrapper
63 * untouchable.
64 */
65const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
66​
67const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
68​
69function QuestionText(props: { readonly markdown: string }) {
70 const styles = useMarkdownPreviewStyles();
71 const openLink = useOpenPullRequest();
72 return (
73 <SelectableMarkdownText
74 markdown={props.markdown}
75 textStyle={styles.nativeTextStyle}
76 onLinkPress={(href) => void openLink(href)}
77 />
78 );
80​
81export function PendingUserInputCard(props: PendingUserInputCardProps) {
82 const questionCount = props.pendingUserInput.questions.length;
83 const canRespond = props.pendingUserInput.responseCapability !== "not_resumable";
84 const isResponding = props.respondingUserInputId === props.pendingUserInput.requestId;
85 const responseDisabled = !canRespond || isResponding;
86​
87 const cardCoverage = props.cardCoverage;
88 const barHeightRef = useRef(0);
89 const cardHeightRef = useRef(0);
90 const cardHeight = useSharedValue(0);
91 const notifyCoverage = useCallback(() => {
92 if (!cardCoverage) {
93 return;
94 }
95 const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
96 if (coverage === cardCoverage.value) {
97 return;
98 }
99 if (cardCoverage.value === 0) {
100 cardCoverage.value = coverage;
101 return;
102 }
103 cardCoverage.value = withTiming(coverage, {
104 duration: USER_INPUT_TOGGLE_DURATION_MS,
105 easing: Easing.out(Easing.cubic),
106 });
107 }, [cardCoverage]);
108 const handleBarLayout = useCallback(
109 (event: LayoutChangeEvent) => {
110 barHeightRef.current = event.nativeEvent.layout.height;
111 notifyCoverage();
112 },
113 [notifyCoverage],
114 );
115 const handleCardLayout = useCallback(
116 (event: LayoutChangeEvent) => {
117 cardHeightRef.current = event.nativeEvent.layout.height;
118 cardHeight.value = event.nativeEvent.layout.height;
119 notifyCoverage();
120 },
121 [cardHeight, notifyCoverage],
122 );
123 const cardProgress = props.cardProgress;
124 const cardAnimatedStyle = useAnimatedStyle(() => {
125 const progress = cardProgress === undefined ? 1 : cardProgress.value;
126 return {
127 transform: [{ translateY: (1 - progress) * cardHeight.value }],
128 };
129 });
130​
131 // On iOS the card stays MOUNTED while collapsed (hidden via the animated
132 // style): expanding animates existing views on the UI thread the same
133 // frame the host starts the progress timing, instead of paying a React
134 // mount + layout before anything moves.
135 const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
136 const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
137 const bar = showBar ? (
138 <View
139 onLayout={handleBarLayout}
140 pointerEvents={props.collapsed ? "auto" : "none"}
141 accessibilityElementsHidden={!props.collapsed}
142 importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
143 className="flex-row items-center gap-2 rounded-full border border-border bg-card-alt py-1.5 pl-4 pr-1.5"
144 >
145 <Pressable
146 accessibilityRole="button"
147 accessibilityLabel={`Expand user input, ${questionCount} question${
148 questionCount === 1 ? "" : "s"
149 }`}
150 onPress={props.onToggleCollapsed}
151 className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
152 >
153 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
154 User input needed
155 </Text>
156 <Text className="font-sans text-xs text-foreground-muted">
157 {questionCount} question{questionCount === 1 ? "" : "s"}
158 </Text>
159 <View className="flex-1" />
160 <SymbolView
161 name="chevron.up"
162 size={12}
163 tintColorClassName={"accent-icon-subtle"}
164 type="monochrome"
165 />
166 </Pressable>
167 {props.onStopThread ? (
168 <ControlPill
169 accessibilityLabel="Stop"
170 icon="stop.fill"
171 variant="danger"
172 className="h-9 w-9"
173 disabled={!props.canOperateThread}
174 onPress={props.onStopThread}
175 />
176 ) : null}
177 </View>
178 ) : null;
179 const card = renderCard ? (
180 <Animated.View
181 onLayout={handleCardLayout}
182 pointerEvents={props.collapsed ? "none" : "auto"}
183 accessibilityElementsHidden={props.collapsed}
184 importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
185 entering={
186 EXPANDED_CARD_IS_OVERLAY
187 ? undefined
188 : FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
189 }
190 exiting={
191 EXPANDED_CARD_IS_OVERLAY
192 ? undefined
193 : FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
194 }
195 layout={CARD_LAYOUT_TRANSITION}
196 className="overflow-hidden gap-2.5 rounded-[20px] border border-border bg-card-alt p-4"
197 style={
198 EXPANDED_CARD_IS_OVERLAY
199 ? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
200 : { maxHeight: props.maxHeight }
201 }
202 >
203 <Pressable
204 accessibilityRole="button"
205 accessibilityLabel="Collapse user input"
206 onPress={props.onToggleCollapsed}
207 className="flex-row items-start gap-2"
208 >
209 <View className="flex-1 gap-2.5">
210 <Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-secondary">
211 User input needed
212 </Text>
213 <Text className="font-t3-bold text-lg text-foreground">Fill in the pending answers</Text>
214 </View>
215 <View className="h-8 w-8 items-center justify-center rounded-full bg-subtle-strong">
216 <SymbolView
217 name="chevron.down"
218 size={13}
219 tintColorClassName={"accent-icon-subtle"}
220 type="monochrome"
221 />
222 </View>
223 </Pressable>
224 <ScrollView
225 bounces={false}
226 className="min-h-0"
227 contentContainerClassName="gap-2.5 pb-1"
228 keyboardShouldPersistTaps="handled"
229 nestedScrollEnabled
230 showsVerticalScrollIndicator
231 style={{ flexShrink: 1 }}
232 >
233 {!canRespond ? (
234 <Text className="font-sans text-sm leading-5 text-foreground-muted">
235 The provider process for this request is no longer available. Interrupt or restart the
236 run to continue.
237 </Text>
238 ) : null}
239 {props.pendingUserInput.questions.map((question) => {
240 const draft = props.drafts[question.id];
241 return (
242 <View key={question.id} className="gap-2 pt-1">
243 <Text className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted">
244 {question.header}
245 </Text>
246 <QuestionText markdown={question.question} />
247 <View className="gap-2">
248 {question.options.map((option) => {
249 const optionValue = option.value ?? option.label.trim();
250 const selected = isPendingUserInputOptionSelected(question, draft, optionValue);
251 const description =
252 option.description !== option.label ? option.description : undefined;
253 return (
254 <Pressable
255 key={optionValue}
256 accessibilityRole={question.multiSelect ? "checkbox" : "radio"}
257 accessibilityState={{ checked: selected, disabled: responseDisabled }}
258 disabled={responseDisabled}
259 className={cn(
260 "min-h-12 w-full rounded-2xl border px-3.5 py-3",
261 selected ? "border-primary bg-primary/10" : "border-border bg-input",
262 )}
263 onPress={() =>
264 props.onSelectOption(
265 props.pendingUserInput.requestId,
266 question,
267 optionValue,
268 )
269 }
270 >
271 <View className="min-w-0 flex-1 gap-0.5">
272 <Text
273 className={cn(
274 "font-t3-bold text-sm",
275 selected ? "text-foreground" : "text-foreground-secondary",
276 )}
277 >
278 {option.label}
279 </Text>
280 {description ? (
281 <Text className="font-sans text-sm leading-5 text-foreground-muted">
282 {description}
283 </Text>
284 ) : null}
285 </View>
286 </Pressable>
287 );
288 })}
289 </View>
290 {question.allowCustomAnswer !== false ? (
291 <QuestionAttachments
292 requestId={props.pendingUserInput.requestId}
293 question={question}
294 questions={props.pendingUserInput.questions}
295 disabled={responseDisabled}
296 value={draft?.customAnswer ?? ""}
297 onChangeText={(value) =>
298 props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
299 }
300 onInputFocusChange={props.onInputFocusChange}
301 />
302 ) : null}
303 </View>
304 );
305 })}
306 </ScrollView>
307 <RequestActionButton
308 label="Submit answers"
309 size="large"
310 tone={props.answers ? "primary" : "secondary"}
311 disabled={!props.canOperateThread || responseDisabled || props.answers === null}
312 onPress={() => void props.onSubmit()}
313 />
314 {props.pendingUserInput.dismissible ? (
315 <Pressable
316 accessibilityRole="button"
317 className="items-center justify-center rounded-2xl px-4 py-2.5 active:opacity-70"
318 disabled={isResponding}
319 onPress={() => void props.onDismiss()}
320 >
321 <Text className="font-t3-bold text-sm text-foreground-muted">
322 Dismiss without answering
323 </Text>
324 </Pressable>
325 ) : null}
326 {!props.canOperateThread ? (
327 <Text className="font-sans text-xs text-foreground-tertiary">
328 This connection cannot submit answers.
329 </Text>
330 ) : null}
331 </Animated.View>
332 ) : null;
333 return (
334 <View className="relative">
335 {bar}
336 {EXPANDED_CARD_IS_OVERLAY ? (
337 <View
338 pointerEvents={props.collapsed ? "none" : "box-none"}
339 className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
340 style={{ height: props.maxHeight }}
341 >
342 {card}
343 </View>
344 ) : (
345 card
346 )}
347 </View>
348 );