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