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

ComposerPendingUserInputPanel.tsx

303 lines11.4 KB

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