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

ComposerPendingUserInputPanel.tsx

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