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

ComposerPendingUserInputPanel.tsx

312 lines11.4 KB

1import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts";
2import { memo, useCallback, useEffect, useRef, useState } from "react";
3import { type PendingUserInput } from "../../session-logic";
4import {
5 derivePendingUserInputProgress,
6 type PendingUserInputDraftAnswer,
7} from "../../pendingUserInput";
8import { CheckIcon } from "lucide-react";
9import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
10import { cn } from "~/lib/utils";
11import { ComposerBanner } from "./ComposerBanner";
12import ChatMarkdown from "../ChatMarkdown";
13​
14interface PendingUserInputPanelProps {
15 pendingUserInputs: PendingUserInput[];
16 cwd: string | undefined;
17 threadRef: ScopedThreadRef;
18 disabled?: boolean;
19 respondingRequestIds: RuntimeRequestId[];
20 answers: Record<string, PendingUserInputDraftAnswer>;
21 questionIndex: number;
22 onToggleOption: (questionId: string, optionValue: string) => void;
23 onAdvance: () => void;
24 onDismiss: (requestId: RuntimeRequestId) => void;
26​
27export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
28 pendingUserInputs,
29 cwd,
30 threadRef,
31 disabled = false,
32 respondingRequestIds,
33 answers,
34 questionIndex,
35 onToggleOption,
36 onAdvance,
37 onDismiss,
38}: PendingUserInputPanelProps) {
39 if (pendingUserInputs.length === 0) return null;
40 const activePrompt = pendingUserInputs[0];
41 if (!activePrompt) return null;
42​
43 return (
44 <ComposerPendingUserInputCard
45 key={activePrompt.requestId}
46 prompt={activePrompt}
47 cwd={cwd}
48 threadRef={threadRef}
49 disabled={disabled}
50 isResponding={respondingRequestIds.includes(activePrompt.requestId)}
51 answers={answers}
52 questionIndex={questionIndex}
53 onToggleOption={onToggleOption}
54 onAdvance={onAdvance}
55 onDismiss={onDismiss}
56 />
57 );
58});
59​
60const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
61 prompt,
62 cwd,
63 threadRef,
64 disabled,
65 isResponding,
66 answers,
67 questionIndex,
68 onToggleOption,
69 onAdvance,
70 onDismiss,
71}: {
72 prompt: PendingUserInput;
73 cwd: string | undefined;
74 threadRef: ScopedThreadRef;
75 disabled: boolean;
76 isResponding: boolean;
77 answers: Record<string, PendingUserInputDraftAnswer>;
78 questionIndex: number;
79 onToggleOption: (questionId: string, optionValue: string) => void;
80 onAdvance: () => void;
81 onDismiss: (requestId: RuntimeRequestId) => void;
82}) {
83 // Message-mode requests remain answerable after their provider turn ends.
84 const canRespond = prompt.responseCapability !== "not_resumable";
85 const responseDisabled = disabled || isResponding || !canRespond;
86 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
87 const activeQuestion = progress.activeQuestion;
88 const autoAdvanceTimerRef = useRef<number | null>(null);
89 const onAdvanceRef = useRef(onAdvance);
90 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
91 questionId: string;
92 optionValue: string;
93 } | null>(null);
94 const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
95 const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
96​
97 useEffect(() => {
98 onAdvanceRef.current = onAdvance;
99 }, [onAdvance]);
100​
101 useEffect(() => {
102 if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
103 return;
104 }
105 if (optimisticSingleSelect.questionId !== activeQuestion.id) {
106 setOptimisticSingleSelect(null);
107 return;
108 }
109 if (
110 progress.customAnswer.trim().length === 0 &&
111 progress.selectedOptionValues.includes(optimisticSingleSelect.optionValue)
112 ) {
113 setOptimisticSingleSelect(null);
114 }
115 }, [
116 activeQuestion,
117 optimisticSingleSelect,
118 progress.customAnswer,
119 progress.selectedOptionValues,
120 ]);
121​
122 // A delayed answer only advances its own question, while permission remains granted.
123 useEffect(() => {
124 const clearAutoAdvance = () => {
125 if (autoAdvanceTimerRef.current !== null) {
126 window.clearTimeout(autoAdvanceTimerRef.current);
127 autoAdvanceTimerRef.current = null;
128 }
129 };
130 if (disabled || activeQuestion?.id === undefined) clearAutoAdvance();
131 return clearAutoAdvance;
132 }, [activeQuestion?.id, disabled]);
133​
134 const handleOptionSelection = useCallback(
135 (questionId: string, optionValue: string) => {
136 if (disabled || isResponding) return;
137 if (activeQuestion?.multiSelect) {
138 onToggleOption(questionId, optionValue);
139 return;
140 }
141 setOptimisticSingleSelect({ questionId, optionValue });
142 onToggleOption(questionId, optionValue);
143 if (autoAdvanceTimerRef.current !== null) {
144 window.clearTimeout(autoAdvanceTimerRef.current);
145 }
146 autoAdvanceTimerRef.current = window.setTimeout(() => {
147 autoAdvanceTimerRef.current = null;
148 onAdvanceRef.current();
149 }, 200);
150 },
151 [activeQuestion, disabled, isResponding, onToggleOption],
152 );
153​
154 useEffect(() => {
155 if (!activeQuestion || responseDisabled || isCollapsed) return;
156 const handler = (event: globalThis.KeyboardEvent) => {
157 if (event.metaKey || event.ctrlKey || event.altKey) return;
158 const target = event.target;
159 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
160 return;
161 }
162 if (
163 target instanceof HTMLElement &&
164 target.closest('[contenteditable]:not([contenteditable="false"])')
165 ) {
166 return;
167 }
168 const digit = Number.parseInt(event.key, 10);
169 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
170 const optionIndex = digit - 1;
171 if (optionIndex >= activeQuestion.options.length) return;
172 const option = activeQuestion.options[optionIndex];
173 if (!option) return;
174 event.preventDefault();
175 handleOptionSelection(activeQuestion.id, option.value ?? option.label);
176 };
177 document.addEventListener("keydown", handler);
178 return () => document.removeEventListener("keydown", handler);
179 }, [activeQuestion, handleOptionSelection, isCollapsed, responseDisabled]);
180​
181 if (!activeQuestion) {
182 return null;
183 }
184​
185 const customAnswerActive = progress.customAnswer.trim().length > 0;
186​
187 return (
188 <Collapsible
189 open={!isCollapsed}
190 onOpenChange={(open) => {
191 setCollapsedQuestionId(open ? null : activeQuestion.id);
192 }}
193 >
194 <CollapsibleTrigger
195 render={<ComposerBanner.Row render={<button type="button" />} />}
196 title={
197 isCollapsed ? "Show the question and its options" : "Hide the question and its options"
198 }
199 data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
200 >
201 <ComposerBanner.Icon />
202 <ComposerBanner.Content>
203 <span className="shrink-0 font-medium text-muted-foreground">
204 {activeQuestion.header}
205 </span>
206 {isCollapsed ? (
207 <span className="min-w-0 flex-1 truncate text-secondary-label">
208 {activeQuestion.question}
209 </span>
210 ) : null}
211 </ComposerBanner.Content>
212 <ComposerBanner.Actions>
213 {prompt.questions.length > 1 ? (
214 <span className="text-3xs font-medium text-muted-foreground tabular-nums">
215 {questionIndex + 1}/{prompt.questions.length}
216 </span>
217 ) : null}
218 <ComposerBanner.ToggleIcon expanded={!isCollapsed} />
219 {prompt.dismissible ? (
220 <ComposerBanner.Dismiss
221 render={<span role="button" tabIndex={0} />}
222 aria-label="Dismiss question without answering"
223 title="Dismiss question without answering"
224 disabled={isResponding}
225 data-pending-user-input-dismiss
226 onClick={(event) => {
227 event.preventDefault();
228 event.stopPropagation();
229 onDismiss(prompt.requestId);
230 }}
231 onKeyDown={(event) => {
232 if (event.key !== "Enter" && event.key !== " ") return;
233 event.preventDefault();
234 event.stopPropagation();
235 onDismiss(prompt.requestId);
236 }}
237 />
238 ) : null}
239 </ComposerBanner.Actions>
240 </CollapsibleTrigger>
241 <CollapsiblePanel>
242 <ComposerBanner.Scroll>
243 <ComposerBanner.Body className="pe-1 pb-1 wrap-anywhere">
244 <ChatMarkdown
245 text={activeQuestion.question}
246 cwd={cwd}
247 threadRef={threadRef}
248 className="text-foreground/85"
249 />
250 {activeQuestion.multiSelect ? (
251 <p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
252 ) : null}
253 <div className="mt-2 space-y-0.5">
254 {activeQuestion.options.map((option, index) => {
255 const optionValue = option.value ?? option.label;
256 const isOptimisticallySelected =
257 optimisticSingleSelect?.questionId === activeQuestion.id &&
258 optimisticSingleSelect.optionValue === optionValue;
259 const isSelected =
260 isOptimisticallySelected ||
261 (!customAnswerActive && progress.selectedOptionValues.includes(optionValue));
262 const shortcutKey = index < 9 ? index + 1 : null;
263 const className = cn(
264 "group flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25",
265 isSelected
266 ? "bg-muted/55 text-foreground"
267 : "bg-transparent text-foreground/85 hover:bg-muted/30",
268 (disabled || isResponding) && "opacity-50 cursor-not-allowed",
269 !disabled && !isResponding && "cursor-pointer",
270 );
271 const content = (
272 <>
273 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
274 <span className="text-sm font-medium">{option.label}</span>
275 {option.description && option.description !== option.label ? (
276 <span className="text-secondary-label text-2xs">{option.description}</span>
277 ) : null}
278 </div>
279 {isSelected ? (
280 <CheckIcon className="size-3.5 shrink-0 text-primary" />
281 ) : shortcutKey !== null ? (
282 <kbd
283 className={cn(
284 "flex size-5 shrink-0 items-center justify-center text-3xs font-medium text-muted-foreground tabular-nums",
285 )}
286 >
287 {shortcutKey}
288 </kbd>
289 ) : null}
290 </>
291 );
292 return (
293 <button
294 key={`${activeQuestion.id}:${optionValue}`}
295 type="button"
296 disabled={disabled || isResponding}
297 onClick={() => {
298 handleOptionSelection(activeQuestion.id, optionValue);
299 }}
300 className={className}
301 >
302 {content}
303 </button>
304 );
305 })}
306 </div>
307 </ComposerBanner.Body>
308 </ComposerBanner.Scroll>
309 </CollapsiblePanel>
310 </Collapsible>
311 );
312});