Open History to see the last commit
1import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts";
2import { markdownProseDirection, textDirection } from "~/textDirection";
3import { memo, use, useEffect, useEffectEvent, useRef, useState } from "react";
4import { BackgroundThreadContext } from "./backgroundThread";
5import { useStableCallback } from "~/hooks/useStableCallback";
6import { type PendingUserInput } from "../../session-logic";
7import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
8import { derivePendingUserInputProgress } from "../../pendingUserInput";
9import { CheckboxMark } from "../ui/checkbox";
10import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
11import { Kbd } from "../ui/kbd";
12import { cn } from "~/lib/utils";
13import { isInSideChatPane } from "~/lib/sideChatPane";
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;
28}
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 (isInSideChatPane(target)) return;
157 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
158 return;
159 }
160 if (
161 target instanceof HTMLElement &&
162 target.closest(
163 'select, [contenteditable]:not([contenteditable="false"]), [role="dialog"], [aria-modal="true"], [role="menu"], [role="combobox"], [data-slot$="popup"]',
164 )
165 ) {
166 return;
167 }
168 const digit = Number.parseInt(event.key, 10);
169 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
170 const optionIndex = digit - 1;
171 if (optionIndex >= activeQuestion.options.length) return;
172 const option = activeQuestion.options[optionIndex];
173 if (!option) return;
174 event.preventDefault();
175 selectOptionFromShortcut(activeQuestion.id, option.value ?? option.label);
176 };
177 document.addEventListener("keydown", handler);
178 return () => document.removeEventListener("keydown", handler);
179 }, [activeQuestion, backgroundThread, isCollapsed, responseDisabled]);
180
181 if (!activeQuestion) {
182 return null;
183 }
184
185 const promptDirection = markdownProseDirection(
186 prompt.questions
187 .flatMap((question) => [
188 question.header,
189 question.question,
190 ...question.options.flatMap((option) => [option.label, option.description ?? ""]),
191 ])
192 .join(" "),
193 );
194 const questionTextAlign = promptDirection === "rtl" ? "text-right" : "text-left";
195
196 return (
197 <Collapsible
198 dir={promptDirection}
199 open={!isCollapsed}
200 onOpenChange={(open) => {
201 setCollapsedQuestionId(open ? null : activeQuestion.id);
202 }}
203 >
204 <CollapsibleTrigger
205 render={<ComposerBanner.Row render={<button type="button" />} />}
206 title={
207 isCollapsed ? "Show the question and its options" : "Hide the question and its options"
208 }
209 data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
210 className="px-4 py-1.5"
211 >
212 <ComposerBanner.Content>
213 <span
214 className={cn("min-w-0 truncate text-muted-foreground", isCollapsed && "max-w-1/2")}
215 dir={textDirection(activeQuestion.header)}
216 >
217 {activeQuestion.header}
218 </span>
219 {isCollapsed ? (
220 <>
221 <ComposerBanner.Separator />
222 <span
223 className={cn("min-w-0 flex-1 truncate text-secondary-label", questionTextAlign)}
224 dir={markdownProseDirection(activeQuestion.question)}
225 >
226 {activeQuestion.question}
227 </span>
228 </>
229 ) : null}
230 </ComposerBanner.Content>
231 <ComposerBanner.Actions className="gap-0">
232 {prompt.questions.length > 1 ? (
233 <ComposerBanner.Count>
234 {questionIndex + 1}/{prompt.questions.length}
235 </ComposerBanner.Count>
236 ) : null}
237 <ComposerBanner.ToggleIcon expanded={!isCollapsed} />
238 {prompt.dismissible ? (
239 <ComposerBanner.Dismiss
240 render={<span role="button" tabIndex={0} />}
241 aria-label="Dismiss question without answering"
242 title="Dismiss question without answering"
243 disabled={isResponding}
244 data-pending-user-input-dismiss
245 onClick={(event) => {
246 event.preventDefault();
247 event.stopPropagation();
248 onDismiss(prompt.requestId);
249 }}
250 onKeyDown={(event) => {
251 if (event.key !== "Enter" && event.key !== " ") return;
252 event.preventDefault();
253 event.stopPropagation();
254 onDismiss(prompt.requestId);
255 }}
256 />
257 ) : null}
258 </ComposerBanner.Actions>
259 </CollapsibleTrigger>
260 <CollapsiblePanel>
261 <ComposerBanner.Scroll>
262 <ComposerBanner.Body className="ps-6 pe-4 pb-1 wrap-anywhere sm:ps-5.5">
263 <ChatMarkdown
264 text={activeQuestion.question}
265 cwd={cwd}
266 threadRef={threadRef}
267 lineBreaks
268 className={cn("pt-0.5 text-foreground/85", questionTextAlign)}
269 />
270 {/* Rows span the header row's width so the radios align with the question text and the shortcut column sits under the dismiss button. */}
271 <div className="-ms-2 mt-1.5 sm:-ms-1.5">
272 {activeQuestion.options.map((option, index) => {
273 const optionValue = option.value ?? option.label;
274 const isOptimisticallySelected =
275 optimisticSingleSelect?.questionId === activeQuestion.id &&
276 optimisticSingleSelect.optionValue === optionValue;
277 const isSelected =
278 isOptimisticallySelected || draftSelectedOptions?.[index] === true;
279 const className = cn(
280 questionTextAlign,
281 "group flex w-full items-start gap-2.5 rounded-md bg-transparent py-1.5 ps-2 sm:ps-1.5 outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25",
282 isSelected ? "text-foreground" : "text-foreground/70 hover:bg-muted/30",
283 (disabled || isResponding) && "opacity-50 cursor-not-allowed",
284 !disabled && !isResponding && "cursor-pointer",
285 );
286 // The h-5 slots match the label's line box, so the indicator and shortcut stay on its first line.
287 const content = (
288 <>
289 <span className="pointer-events-none flex h-5 shrink-0 items-center">
290 {activeQuestion.multiSelect ? (
291 <CheckboxMark checked={isSelected} variant="contrast" />
292 ) : (
293 <OptionRadio checked={isSelected} />
294 )}
295 </span>
296 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
297 <span className="text-sm font-medium" dir={textDirection(option.label)}>
298 {option.label}
299 </span>
300 {option.description && option.description !== option.label ? (
301 <span
302 className="text-secondary-label text-2xs"
303 dir={textDirection(option.description)}
304 >
305 {option.description}
306 </span>
307 ) : null}
308 </div>
309 {index < 9 ? (
310 <span className="flex h-5 w-7 shrink-0 items-center justify-center sm:w-6">
311 <Kbd>{index + 1}</Kbd>
312 </span>
313 ) : null}
314 </>
315 );
316 // The preview sits outside the button: it can hold links, and a click on a single-select option advances.
317 return (
318 <div key={`${activeQuestion.id}:${optionValue}`}>
319 <button
320 type="button"
321 aria-pressed={isSelected}
322 disabled={disabled || isResponding}
323 onClick={() => {
324 handleOptionSelection(activeQuestion.id, optionValue);
325 }}
326 className={className}
327 >
328 {content}
329 </button>
330 {option.preview ? (
331 <ChatMarkdown
332 text={option.preview}
333 cwd={cwd}
334 threadRef={threadRef}
335 lineBreaks
336 className="ps-9 pe-2 pb-1.5 text-xs text-foreground/70 sm:ps-8"
337 />
338 ) : null}
339 </div>
340 );
341 })}
342 </div>
343 </ComposerBanner.Body>
344 </ComposerBanner.Scroll>
345 </CollapsiblePanel>
346 </Collapsible>
347 );
348});
349
350// Drawn with ui/radio-group's look instead of using its Radio: Radio only checks inside a
351// RadioGroup, whose arrow keys select options and would trip the single-select auto-advance.
352function OptionRadio({ checked }: { checked: boolean }) {
353 return (
354 <span
355 aria-hidden
356 className={cn(
357 "relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-full border border-foreground/55 bg-background not-dark:bg-clip-padding sm:size-4 dark:bg-input/32",
358 checked ? "shadow-none" : "shadow-xs/5",
359 )}
360 >
361 {checked ? (
362 <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" />
363 ) : null}
364 </span>
365 );
366}