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

PendingUserInputCard.tsx

365 lines14.0 KB

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