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

ComposerPendingUserInputPanel.tsx

312 lines11.9 KB

1import { type RuntimeRequestId } 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";
12​
13interface PendingUserInputPanelProps {
14 pendingUserInputs: PendingUserInput[];
15 disabled?: boolean;
16 respondingRequestIds: RuntimeRequestId[];
17 answers: Record<string, PendingUserInputDraftAnswer>;
18 questionIndex: number;
19 onToggleOption: (questionId: string, optionValue: string) => void;
20 onAdvance: () => void;
21 onDismiss: (requestId: RuntimeRequestId) => void;
23​
24export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
25 pendingUserInputs,
26 disabled = false,
27 respondingRequestIds,
28 answers,
29 questionIndex,
30 onToggleOption,
31 onAdvance,
32 onDismiss,
33}: PendingUserInputPanelProps) {
34 if (pendingUserInputs.length === 0) return null;
35 const activePrompt = pendingUserInputs[0];
36 if (!activePrompt) return null;
37​
38 return (
39 <ComposerPendingUserInputCard
40 key={activePrompt.requestId}
41 prompt={activePrompt}
42 disabled={disabled}
43 isResponding={respondingRequestIds.includes(activePrompt.requestId)}
44 answers={answers}
45 questionIndex={questionIndex}
46 onToggleOption={onToggleOption}
47 onAdvance={onAdvance}
48 onDismiss={onDismiss}
49 />
50 );
51});
52​
53const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
54 prompt,
55 disabled,
56 isResponding,
57 answers,
58 questionIndex,
59 onToggleOption,
60 onAdvance,
61 onDismiss,
62}: {
63 prompt: PendingUserInput;
64 disabled: boolean;
65 isResponding: boolean;
66 answers: Record<string, PendingUserInputDraftAnswer>;
67 questionIndex: number;
68 onToggleOption: (questionId: string, optionValue: string) => void;
69 onAdvance: () => void;
70 onDismiss: (requestId: RuntimeRequestId) => void;
71}) {
72 // Message-mode requests remain answerable after their provider turn ends.
73 const canRespond = prompt.responseCapability !== "not_resumable";
74 const responseDisabled = disabled || isResponding || !canRespond;
75 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
76 const activeQuestion = progress.activeQuestion;
77 const autoAdvanceTimerRef = useRef<number | null>(null);
78 const onAdvanceRef = useRef(onAdvance);
79 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
80 questionId: string;
81 optionValue: string;
82 } | null>(null);
83 // Collapsing hides everything but the header so a tall prompt stops covering
84 // the thread the user is trying to read. Scoped to a single question: the card
85 // is keyed by request id so the next prompt starts expanded, and storing the
86 // collapsed question's id (rather than a bare flag) reopens the card when the
87 // prompt advances to its next question, which can happen without a click —
88 // sending from the composer advances the active question.
89 const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
90 const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
91​
92 useEffect(() => {
93 onAdvanceRef.current = onAdvance;
94 }, [onAdvance]);
95​
96 useEffect(() => {
97 if (disabled && autoAdvanceTimerRef.current !== null) {
98 window.clearTimeout(autoAdvanceTimerRef.current);
99 autoAdvanceTimerRef.current = null;
100 }
101 }, [disabled]);
102​
103 useEffect(() => {
104 if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
105 return;
106 }
107 if (optimisticSingleSelect.questionId !== activeQuestion.id) {
108 setOptimisticSingleSelect(null);
109 return;
110 }
111 if (
112 progress.customAnswer.trim().length === 0 &&
113 progress.selectedOptionValues.includes(optimisticSingleSelect.optionValue)
114 ) {
115 setOptimisticSingleSelect(null);
116 }
117 }, [
118 activeQuestion,
119 optimisticSingleSelect,
120 progress.customAnswer,
121 progress.selectedOptionValues,
122 ]);
123​
124 // Clear auto-advance timer on unmount
125 useEffect(() => {
126 return () => {
127 if (autoAdvanceTimerRef.current !== null) {
128 window.clearTimeout(autoAdvanceTimerRef.current);
129 }
130 };
131 }, []);
132​
133 const handleOptionSelection = useCallback(
134 (questionId: string, optionValue: string) => {
135 if (disabled || isResponding) return;
136 if (activeQuestion?.multiSelect) {
137 onToggleOption(questionId, optionValue);
138 return;
139 }
140 setOptimisticSingleSelect({ questionId, optionValue });
141 onToggleOption(questionId, optionValue);
142 if (autoAdvanceTimerRef.current !== null) {
143 window.clearTimeout(autoAdvanceTimerRef.current);
144 }
145 autoAdvanceTimerRef.current = window.setTimeout(() => {
146 autoAdvanceTimerRef.current = null;
147 onAdvanceRef.current();
148 }, 200);
149 },
150 [activeQuestion, disabled, isResponding, onToggleOption],
151 );
152​
153 // Keyboard shortcut: number keys 1-9 select corresponding options when focus is
154 // outside editable fields. Multi-select prompts toggle options in place; single-
155 // select prompts keep the existing auto-advance behavior. Collapsed prompts opt
156 // out, since the numbers they refer to are not on screen.
157 useEffect(() => {
158 if (!activeQuestion || responseDisabled || isCollapsed) return;
159 const handler = (event: globalThis.KeyboardEvent) => {
160 if (event.metaKey || event.ctrlKey || event.altKey) return;
161 const target = event.target;
162 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
163 return;
164 }
165 if (
166 target instanceof HTMLElement &&
167 target.closest('[contenteditable]:not([contenteditable="false"])')
168 ) {
169 return;
170 }
171 const digit = Number.parseInt(event.key, 10);
172 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
173 const optionIndex = digit - 1;
174 if (optionIndex >= activeQuestion.options.length) return;
175 const option = activeQuestion.options[optionIndex];
176 if (!option) return;
177 event.preventDefault();
178 handleOptionSelection(activeQuestion.id, option.value ?? option.label);
179 };
180 document.addEventListener("keydown", handler);
181 return () => document.removeEventListener("keydown", handler);
182 }, [activeQuestion, handleOptionSelection, isCollapsed, responseDisabled]);
183​
184 if (!activeQuestion) {
185 return null;
186 }
187​
188 const customAnswerActive = progress.customAnswer.trim().length > 0;
189​
190 return (
191 <Collapsible
192 open={!isCollapsed}
193 onOpenChange={(open) => {
194 setCollapsedQuestionId(open ? null : activeQuestion.id);
195 }}
196 >
197 <CollapsibleTrigger
198 render={<ComposerBanner.Row render={<button type="button" />} />}
199 title={
200 isCollapsed ? "Show the question and its options" : "Hide the question and its options"
201 }
202 data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
203 >
204 <ComposerBanner.Icon />
205 <ComposerBanner.Content>
206 <span className="shrink-0 font-medium text-muted-foreground">
207 {activeQuestion.header}
208 </span>
209 {isCollapsed ? (
210 <span className="min-w-0 flex-1 truncate text-secondary-label">
211 {activeQuestion.question}
212 </span>
213 ) : null}
214 </ComposerBanner.Content>
215 <ComposerBanner.Actions>
216 {prompt.questions.length > 1 ? (
217 <span className="text-3xs font-medium text-muted-foreground tabular-nums">
218 {questionIndex + 1}/{prompt.questions.length}
219 </span>
220 ) : null}
221 <ComposerBanner.ToggleIcon expanded={!isCollapsed} />
222 {prompt.dismissible ? (
223 // Sits inside the trigger button, so stop the click from toggling
224 // the disclosure. Dismiss closes the question without a reply.
225 <ComposerBanner.Dismiss
226 render={<span role="button" tabIndex={0} />}
227 aria-label="Dismiss question without answering"
228 title="Dismiss question without answering"
229 disabled={isResponding}
230 data-pending-user-input-dismiss
231 onClick={(event) => {
232 event.preventDefault();
233 event.stopPropagation();
234 onDismiss(prompt.requestId);
235 }}
236 onKeyDown={(event) => {
237 if (event.key !== "Enter" && event.key !== " ") return;
238 event.preventDefault();
239 event.stopPropagation();
240 onDismiss(prompt.requestId);
241 }}
242 />
243 ) : null}
244 </ComposerBanner.Actions>
245 </CollapsibleTrigger>
246 <CollapsiblePanel>
247 <ComposerBanner.Scroll>
248 <ComposerBanner.Body className="pe-1 pb-1 wrap-anywhere">
249 <p className="text-sm text-foreground/85">{activeQuestion.question}</p>
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-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});