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