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

ComposerPendingUserInputPanel.tsx

323 lines12.7 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 { CheckboxMark } from "../ui/checkbox";
11import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
12import { Kbd } from "../ui/kbd";
13import { cn } from "~/lib/utils";
14import { ComposerBanner } from "./ComposerBanner";
15import ChatMarkdown from "../ChatMarkdown";
16​
17interface PendingUserInputPanelProps {
18 pendingUserInputs: PendingUserInput[];
19 cwd: string | undefined;
20 threadRef: ScopedThreadRef;
21 disabled?: boolean;
22 respondingRequestIds: RuntimeRequestId[];
23 answers: Record<string, PendingUserInputDraftAnswer>;
24 questionIndex: number;
25 onToggleOption: (questionId: string, optionValue: string) => void;
26 onAdvance: () => void;
27 onDismiss: (requestId: RuntimeRequestId) => void;
29​
30export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
31 pendingUserInputs,
32 cwd,
33 threadRef,
34 disabled = false,
35 respondingRequestIds,
36 answers,
37 questionIndex,
38 onToggleOption,
39 onAdvance,
40 onDismiss,
41}: PendingUserInputPanelProps) {
42 if (pendingUserInputs.length === 0) return null;
43 const activePrompt = pendingUserInputs[0];
44 if (!activePrompt) return null;
45​
46 return (
47 <ComposerPendingUserInputCard
48 key={activePrompt.requestId}
49 prompt={activePrompt}
50 cwd={cwd}
51 threadRef={threadRef}
52 disabled={disabled}
53 isResponding={respondingRequestIds.includes(activePrompt.requestId)}
54 answers={answers}
55 questionIndex={questionIndex}
56 onToggleOption={onToggleOption}
57 onAdvance={onAdvance}
58 onDismiss={onDismiss}
59 />
60 );
61});
62​
63const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
64 prompt,
65 cwd,
66 threadRef,
67 disabled,
68 isResponding,
69 answers,
70 questionIndex,
71 onToggleOption,
72 onAdvance,
73 onDismiss,
74}: {
75 prompt: PendingUserInput;
76 cwd: string | undefined;
77 threadRef: ScopedThreadRef;
78 disabled: boolean;
79 isResponding: boolean;
80 answers: Record<string, PendingUserInputDraftAnswer>;
81 questionIndex: number;
82 onToggleOption: (questionId: string, optionValue: string) => void;
83 onAdvance: () => void;
84 onDismiss: (requestId: RuntimeRequestId) => void;
85}) {
86 // Message-mode requests remain answerable after their provider turn ends.
87 const canRespond = prompt.responseCapability !== "not_resumable";
88 const responseDisabled = disabled || isResponding || !canRespond;
89 const autoAdvanceTimerRef = useRef<number | null>(null);
90 const advance = useStableCallback(onAdvance);
91 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
92 questionId: string;
93 optionValue: string;
94 } | null>(null);
95 const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
96 // Keep question identity stable for its shortcut listener.
97 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
98 const activeQuestion = progress.activeQuestion;
99 const customAnswerActive = progress.customAnswer.trim().length > 0;
100 // Read before later hooks to preserve the question's compiler cache.
101 const draftSelectedOptions = activeQuestion?.options.map(
102 (option) =>
103 !customAnswerActive && progress.selectedOptionValues.includes(option.value ?? option.label),
104 );
105 const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
106​
107 if (
108 optimisticSingleSelect &&
109 activeQuestion &&
110 !activeQuestion.multiSelect &&
111 (optimisticSingleSelect.questionId !== activeQuestion.id ||
112 (!customAnswerActive &&
113 progress.selectedOptionValues.includes(optimisticSingleSelect.optionValue)))
114 ) {
115 setOptimisticSingleSelect(null);
116 }
117​
118 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the auto-advance timer when the question changes, input is disabled, or the panel unmounts
119 useEffect(() => {
120 const clearAutoAdvance = () => {
121 if (autoAdvanceTimerRef.current !== null) {
122 window.clearTimeout(autoAdvanceTimerRef.current);
123 autoAdvanceTimerRef.current = null;
124 }
125 };
126 if (disabled || activeQuestion?.id === undefined) clearAutoAdvance();
127 return clearAutoAdvance;
128 }, [activeQuestion?.id, disabled]);
129​
130 const handleOptionSelection = (questionId: string, optionValue: string) => {
131 if (disabled || isResponding) return;
132 if (activeQuestion?.multiSelect) {
133 onToggleOption(questionId, optionValue);
134 return;
135 }
136 setOptimisticSingleSelect({ questionId, optionValue });
137 onToggleOption(questionId, optionValue);
138 if (autoAdvanceTimerRef.current !== null) {
139 window.clearTimeout(autoAdvanceTimerRef.current);
140 }
141 autoAdvanceTimerRef.current = window.setTimeout(() => {
142 autoAdvanceTimerRef.current = null;
143 advance();
144 }, 200);
145 };
146​
147 const selectOptionFromShortcut = useEffectEvent(handleOptionSelection);
148 const backgroundThread = use(BackgroundThreadContext);
149​
150 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a document keydown listener for digit shortcuts while a question is answerable
151 useEffect(() => {
152 if (!activeQuestion || responseDisabled || isCollapsed || backgroundThread) return;
153 const handler = (event: globalThis.KeyboardEvent) => {
154 if (event.metaKey || event.ctrlKey || event.altKey) return;
155 const target = event.target;
156 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
157 return;
158 }
159 if (
160 target instanceof HTMLElement &&
161 target.closest('[contenteditable]:not([contenteditable="false"])')
162 ) {
163 return;
164 }
165 const digit = Number.parseInt(event.key, 10);
166 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
167 const optionIndex = digit - 1;
168 if (optionIndex >= activeQuestion.options.length) return;
169 const option = activeQuestion.options[optionIndex];
170 if (!option) return;
171 event.preventDefault();
172 selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label);
173 };
174 document.addEventListener("keydown", handler);
175 return () => document.removeEventListener("keydown", handler);
176 }, [activeQuestion, backgroundThread, isCollapsed, responseDisabled]);
177​
178 if (!activeQuestion) {
179 return null;
180 }
181​
182 return (
183 <Collapsible
184 open={!isCollapsed}
185 onOpenChange={(open) => {
186 setCollapsedQuestionId(open ? null : activeQuestion.id);
187 }}
188 >
189 <CollapsibleTrigger
190 render={<ComposerBanner.Row render={<button type="button" />} />}
191 title={
192 isCollapsed ? "Show the question and its options" : "Hide the question and its options"
193 }
194 data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
195 className="px-4 pt-1.5"
196 >
197 <ComposerBanner.Content>
198 <span className="shrink-0 text-muted-foreground">{activeQuestion.header}</span>
199 {isCollapsed ? (
200 <>
201 <ComposerBanner.Separator />
202 <span className="min-w-0 flex-1 truncate text-secondary-label">
203 {activeQuestion.question}
204 </span>
205 </>
206 ) : null}
207 </ComposerBanner.Content>
208 <ComposerBanner.Actions className="gap-0">
209 {prompt.questions.length > 1 ? (
210 <ComposerBanner.Count>
211 {questionIndex + 1}/{prompt.questions.length}
212 </ComposerBanner.Count>
213 ) : null}
214 <ComposerBanner.ToggleIcon expanded={!isCollapsed} />
215 {prompt.dismissible ? (
216 <ComposerBanner.Dismiss
217 render={<span role="button" tabIndex={0} />}
218 aria-label="Dismiss question without answering"
219 title="Dismiss question without answering"
220 disabled={isResponding}
221 data-pending-user-input-dismiss
222 onClick={(event) => {
223 event.preventDefault();
224 event.stopPropagation();
225 onDismiss(prompt.requestId);
226 }}
227 onKeyDown={(event) => {
228 if (event.key !== "Enter" && event.key !== " ") return;
229 event.preventDefault();
230 event.stopPropagation();
231 onDismiss(prompt.requestId);
232 }}
233 />
234 ) : null}
235 </ComposerBanner.Actions>
236 </CollapsibleTrigger>
237 <CollapsiblePanel>
238 <ComposerBanner.Scroll>
239 <ComposerBanner.Body className="ps-6 pe-4 pb-1 wrap-anywhere sm:ps-5.5">
240 <ChatMarkdown
241 text={activeQuestion.question}
242 cwd={cwd}
243 threadRef={threadRef}
244 className="pt-2 text-foreground/85"
245 />
246 {/* Rows span the header row's width so the radios align with the question text and the shortcut column sits under the dismiss button. */}
247 <div className="-ms-2 mt-1.5 sm:-ms-1.5">
248 {activeQuestion.options.map((option, index) => {
249 const optionValue = option.value ?? option.label;
250 const isOptimisticallySelected =
251 optimisticSingleSelect?.questionId === activeQuestion.id &&
252 optimisticSingleSelect.optionValue === optionValue;
253 const isSelected =
254 isOptimisticallySelected || draftSelectedOptions?.[index] === true;
255 const className = cn(
256 "group flex w-full items-start gap-2.5 rounded-md bg-transparent py-1.5 ps-2 text-left sm:ps-1.5 outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25",
257 isSelected ? "text-foreground" : "text-foreground/70 hover:bg-muted/30",
258 (disabled || isResponding) && "opacity-50 cursor-not-allowed",
259 !disabled && !isResponding && "cursor-pointer",
260 );
261 // The h-5 slots match the label's line box, so the indicator and shortcut stay on its first line.
262 const content = (
263 <>
264 <span className="pointer-events-none flex h-5 shrink-0 items-center">
265 {activeQuestion.multiSelect ? (
266 <CheckboxMark checked={isSelected} />
267 ) : (
268 <OptionRadio checked={isSelected} />
269 )}
270 </span>
271 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
272 <span className="text-sm font-medium">{option.label}</span>
273 {option.description && option.description !== option.label ? (
274 <span className="text-secondary-label text-2xs">{option.description}</span>
275 ) : null}
276 </div>
277 {index < 9 ? (
278 <span className="flex h-5 w-7 shrink-0 items-center justify-center sm:w-6">
279 <Kbd>{index + 1}</Kbd>
280 </span>
281 ) : null}
282 </>
283 );
284 return (
285 <button
286 key={`${activeQuestion.id}:${optionValue}`}
287 type="button"
288 aria-pressed={isSelected}
289 disabled={disabled || isResponding}
290 onClick={() => {
291 handleOptionSelection(activeQuestion.id, optionValue);
292 }}
293 className={className}
294 >
295 {content}
296 </button>
297 );
298 })}
299 </div>
300 </ComposerBanner.Body>
301 </ComposerBanner.Scroll>
302 </CollapsiblePanel>
303 </Collapsible>
304 );
305});
306​
307// Drawn with ui/radio-group's look instead of using its Radio: Radio only checks inside a
308// RadioGroup, whose arrow keys select options and would trip the single-select auto-advance.
309function OptionRadio({ checked }: { checked: boolean }) {
310 return (
311 <span
312 aria-hidden
313 className={cn(
314 "relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-full border border-input bg-background not-dark:bg-clip-padding sm:size-4 dark:bg-input/32",
315 checked ? "shadow-none" : "shadow-xs/5",
316 )}
317 >
318 {checked ? (
319 <span className="-inset-px absolute flex items-center justify-center rounded-full bg-primary before:size-2 before:rounded-full before:bg-primary-foreground sm:before:size-1.5" />
320 ) : null}
321 </span>
322 );