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

ComposerPendingUserInputPanel.tsx

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