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

PendingUserInputCard.tsx

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