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

PendingUserInputCard.tsx

399 lines15.4 KB

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