@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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