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

ComposerPendingUserInputPanel.tsx

310 lines11.6 KB

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