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

ComposerPendingUserInputPanel.tsx

372 lines14.7 KB

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