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

ComposerPendingUserInputPanel.tsx

284 lines11.5 KB

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, ChevronDownIcon } from "lucide-react";
9import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
10import { cn } from "~/lib/utils";
11​
12interface PendingUserInputPanelProps {
13 pendingUserInputs: PendingUserInput[];
14 respondingRequestIds: ApprovalRequestId[];
15 answers: Record<string, PendingUserInputDraftAnswer>;
16 questionIndex: number;
17 onToggleOption: (questionId: string, optionLabel: string) => void;
18 onAdvance: () => void;
20​
21export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
22 pendingUserInputs,
23 respondingRequestIds,
24 answers,
25 questionIndex,
26 onToggleOption,
27 onAdvance,
28}: PendingUserInputPanelProps) {
29 if (pendingUserInputs.length === 0) return null;
30 const activePrompt = pendingUserInputs[0];
31 if (!activePrompt) return null;
32​
33 return (
34 <ComposerPendingUserInputCard
35 key={activePrompt.requestId}
36 prompt={activePrompt}
37 isResponding={respondingRequestIds.includes(activePrompt.requestId)}
38 answers={answers}
39 questionIndex={questionIndex}
40 onToggleOption={onToggleOption}
41 onAdvance={onAdvance}
42 />
43 );
44});
45​
46const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
47 prompt,
48 isResponding,
49 answers,
50 questionIndex,
51 onToggleOption,
52 onAdvance,
53}: {
54 prompt: PendingUserInput;
55 isResponding: boolean;
56 answers: Record<string, PendingUserInputDraftAnswer>;
57 questionIndex: number;
58 onToggleOption: (questionId: string, optionLabel: string) => void;
59 onAdvance: () => void;
60}) {
61 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
62 const activeQuestion = progress.activeQuestion;
63 const autoAdvanceTimerRef = useRef<number | null>(null);
64 const onAdvanceRef = useRef(onAdvance);
65 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
66 questionId: string;
67 optionLabel: string;
68 } | null>(null);
69 // Collapsing hides everything but the header so a tall prompt stops covering
70 // the thread the user is trying to read. Scoped to a single question: the card
71 // is keyed by request id so the next prompt starts expanded, and storing the
72 // collapsed question's id (rather than a bare flag) reopens the card when the
73 // prompt advances to its next question, which can happen without a click —
74 // sending from the composer advances the active question.
75 const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
76 const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
77​
78 useEffect(() => {
79 onAdvanceRef.current = onAdvance;
80 }, [onAdvance]);
81​
82 useEffect(() => {
83 if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
84 return;
85 }
86 if (optimisticSingleSelect.questionId !== activeQuestion.id) {
87 setOptimisticSingleSelect(null);
88 return;
89 }
90 if (
91 progress.customAnswer.trim().length === 0 &&
92 progress.selectedOptionLabels.includes(optimisticSingleSelect.optionLabel)
93 ) {
94 setOptimisticSingleSelect(null);
95 }
96 }, [
97 activeQuestion,
98 optimisticSingleSelect,
99 progress.customAnswer,
100 progress.selectedOptionLabels,
101 ]);
102​
103 // Clear auto-advance timer on unmount
104 useEffect(() => {
105 return () => {
106 if (autoAdvanceTimerRef.current !== null) {
107 window.clearTimeout(autoAdvanceTimerRef.current);
108 }
109 };
110 }, []);
111​
112 const handleOptionSelection = useCallback(
113 (questionId: string, optionLabel: string) => {
114 if (activeQuestion?.multiSelect) {
115 onToggleOption(questionId, optionLabel);
116 return;
117 }
118 setOptimisticSingleSelect({ questionId, optionLabel });
119 onToggleOption(questionId, optionLabel);
120 if (autoAdvanceTimerRef.current !== null) {
121 window.clearTimeout(autoAdvanceTimerRef.current);
122 }
123 autoAdvanceTimerRef.current = window.setTimeout(() => {
124 autoAdvanceTimerRef.current = null;
125 onAdvanceRef.current();
126 }, 200);
127 },
128 [activeQuestion, onToggleOption],
129 );
130​
131 // Keyboard shortcut: number keys 1-9 select corresponding options when focus is
132 // outside editable fields. Multi-select prompts toggle options in place; single-
133 // select prompts keep the existing auto-advance behavior. Collapsed prompts opt
134 // out, since the numbers they refer to are not on screen.
135 useEffect(() => {
136 if (!activeQuestion || isResponding || isCollapsed) return;
137 const handler = (event: globalThis.KeyboardEvent) => {
138 if (event.metaKey || event.ctrlKey || event.altKey) return;
139 const target = event.target;
140 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
141 return;
142 }
143 if (
144 target instanceof HTMLElement &&
145 target.closest('[contenteditable]:not([contenteditable="false"])')
146 ) {
147 return;
148 }
149 const digit = Number.parseInt(event.key, 10);
150 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
151 const optionIndex = digit - 1;
152 if (optionIndex >= activeQuestion.options.length) return;
153 const option = activeQuestion.options[optionIndex];
154 if (!option) return;
155 event.preventDefault();
156 handleOptionSelection(activeQuestion.id, option.label);
157 };
158 document.addEventListener("keydown", handler);
159 return () => document.removeEventListener("keydown", handler);
160 }, [activeQuestion, handleOptionSelection, isCollapsed, isResponding]);
161​
162 if (!activeQuestion) {
163 return null;
164 }
165​
166 const customAnswerActive = progress.customAnswer.trim().length > 0;
167​
168 return (
169 <Collapsible
170 className="py-3"
171 open={!isCollapsed}
172 onOpenChange={(open) => {
173 setCollapsedQuestionId(open ? null : activeQuestion.id);
174 }}
175 >
176 {/* The trigger's wrapper is inset less than the card's text column, and
177 the trigger pays the difference back as padding: the hover background
178 and focus ring bleed 10px past that column on both sides, while the
179 header label and the chevron still line up with the left and right
180 edges of the question text below. The negative block margin keeps the
181 taller hit area from pushing the panel down. */}
182 <div className="px-1.5 sm:px-2.5">
183 <CollapsibleTrigger
184 title={
185 isCollapsed ? "Show the question and its options" : "Hide the question and its options"
186 }
187 data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
188 className="group -my-1 flex w-full items-center gap-3 rounded-md px-2.5 py-1.5 text-left outline-none transition-colors duration-150 hover:bg-muted/40 focus-visible:ring-1 focus-visible:ring-primary/25"
189 >
190 <span className="text-secondary-label text-[11px] font-semibold tracking-widest uppercase group-hover:text-foreground">
191 {activeQuestion.header}
192 </span>
193 {prompt.questions.length > 1 ? (
194 <span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-secondary-label text-[10px] font-medium tabular-nums">
195 {questionIndex + 1}/{prompt.questions.length}
196 </span>
197 ) : null}
198 {/* Collapsed, the header is otherwise just a section label and a
199 counter, so the question itself is echoed here as a one-line
200 reminder of what is being asked. */}
201 {isCollapsed ? (
202 <span className="min-w-0 flex-1 truncate text-secondary-label text-xs">
203 {activeQuestion.question}
204 </span>
205 ) : null}
206 {/* The chevron points at the body: down while it is open below the
207 header, up while it is collapsed into it. */}
208 <ChevronDownIcon
209 aria-hidden="true"
210 className={cn(
211 "ml-auto size-3.5 shrink-0 text-secondary-label transition-transform duration-150 group-hover:text-foreground",
212 isCollapsed && "rotate-180",
213 )}
214 />
215 </CollapsibleTrigger>
216 </div>
217 {/* The panel carries the horizontal padding itself: it clips its content
218 while the height animates, so the option buttons have to sit inside
219 that padding or their focus rings get shaved off at the edges. */}
220 <CollapsiblePanel className="px-4 sm:px-5">
221 <div className="pt-2 pb-0.5">
222 <p className="text-sm text-foreground/90">{activeQuestion.question}</p>
223 {activeQuestion.multiSelect ? (
224 <p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
225 ) : null}
226 <div className="mt-3 space-y-1.5">
227 {activeQuestion.options.map((option, index) => {
228 const isOptimisticallySelected =
229 optimisticSingleSelect?.questionId === activeQuestion.id &&
230 optimisticSingleSelect.optionLabel === option.label;
231 const isSelected =
232 isOptimisticallySelected ||
233 (!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
234 const shortcutKey = index < 9 ? index + 1 : null;
235 const className = cn(
236 "group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-all duration-150 focus-visible:border-primary/40 focus-visible:ring-1 focus-visible:ring-primary/25",
237 isSelected
238 ? "border-primary/30 bg-primary/8 text-foreground"
239 : "border-transparent bg-muted/22 text-foreground/85 hover:border-border/45 hover:bg-muted/34",
240 isResponding && "opacity-50 cursor-not-allowed",
241 !isResponding && "cursor-pointer",
242 );
243 const content = (
244 <>
245 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
246 <span className="text-sm font-medium">{option.label}</span>
247 {option.description && option.description !== option.label ? (
248 <span className="text-secondary-label text-xs">{option.description}</span>
249 ) : null}
250 </div>
251 {isSelected ? (
252 <CheckIcon className="size-3.5 shrink-0 text-primary" />
253 ) : shortcutKey !== null ? (
254 <kbd
255 className={cn(
256 "flex size-5 shrink-0 items-center justify-center rounded border border-border/50 text-[11px] font-medium tabular-nums transition-colors duration-150",
257 "bg-background/35 text-secondary-label group-hover:border-border/70 group-hover:text-foreground",
258 )}
259 >
260 {shortcutKey}
261 </kbd>
262 ) : null}
263 </>
264 );
265 return (
266 <button
267 key={`${activeQuestion.id}:${option.label}`}
268 type="button"
269 disabled={isResponding}
270 onClick={() => {
271 handleOptionSelection(activeQuestion.id, option.label);
272 }}
273 className={className}
274 >
275 {content}
276 </button>
277 );
278 })}
279 </div>
280 </div>
281 </CollapsiblePanel>
282 </Collapsible>
283 );
284});