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

ComposerPendingUserInputPanel.tsx

237 lines8.6 KB

1import { type RuntimeRequestId } from "@t3tools/contracts";
2import { memo, useEffect, useEffectEvent, useRef, useState } from "react";
3import { type PendingUserInput } from "../../session-logic";
4import {
5 derivePendingUserInputProgress,
6 type PendingUserInputDraftAnswer,
7} from "../../pendingUserInput";
8import { CheckIcon } from "lucide-react";
9import { cn } from "~/lib/utils";
10​
11interface PendingUserInputPanelProps {
12 pendingUserInputs: PendingUserInput[];
13 respondingRequestIds: RuntimeRequestId[];
14 answers: Record<string, PendingUserInputDraftAnswer>;
15 questionIndex: number;
16 onToggleOption: (questionId: string, optionLabel: string) => void;
17 onAdvance: () => void;
19​
20export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
21 pendingUserInputs,
22 respondingRequestIds,
23 answers,
24 questionIndex,
25 onToggleOption,
26 onAdvance,
27}: PendingUserInputPanelProps) {
28 if (pendingUserInputs.length === 0) return null;
29 const activePrompt = pendingUserInputs[0];
30 if (!activePrompt) return null;
31​
32 return (
33 <ComposerPendingUserInputCard
34 key={activePrompt.requestId}
35 prompt={activePrompt}
36 isResponding={respondingRequestIds.includes(activePrompt.requestId)}
37 answers={answers}
38 questionIndex={questionIndex}
39 onToggleOption={onToggleOption}
40 onAdvance={onAdvance}
41 />
42 );
43});
44​
45const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
46 prompt,
47 isResponding,
48 answers,
49 questionIndex,
50 onToggleOption,
51 onAdvance,
52}: {
53 prompt: PendingUserInput;
54 isResponding: boolean;
55 answers: Record<string, PendingUserInputDraftAnswer>;
56 questionIndex: number;
57 onToggleOption: (questionId: string, optionLabel: string) => void;
58 onAdvance: () => void;
59}) {
60 const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
61 const activeQuestion = progress.activeQuestion;
62 const canRespond = prompt.responseCapability === "live";
63 const responseDisabled = isResponding || !canRespond;
64 const autoAdvanceTimerRef = useRef<number | null>(null);
65 const onAdvanceRef = useRef(onAdvance);
66 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
67 questionId: string;
68 optionLabel: string;
69 } | null>(null);
70​
71 useEffect(() => {
72 onAdvanceRef.current = onAdvance;
73 }, [onAdvance]);
74​
75 useEffect(() => {
76 if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
77 return;
78 }
79 if (optimisticSingleSelect.questionId !== activeQuestion.id) {
80 setOptimisticSingleSelect(null);
81 return;
82 }
83 if (
84 progress.customAnswer.trim().length === 0 &&
85 progress.selectedOptionLabels.includes(optimisticSingleSelect.optionLabel)
86 ) {
87 setOptimisticSingleSelect(null);
88 }
89 }, [
90 activeQuestion,
91 optimisticSingleSelect,
92 progress.customAnswer,
93 progress.selectedOptionLabels,
94 ]);
95​
96 // Clear auto-advance timer on unmount
97 useEffect(() => {
98 return () => {
99 if (autoAdvanceTimerRef.current !== null) {
100 window.clearTimeout(autoAdvanceTimerRef.current);
101 }
102 };
103 }, []);
104​
105 const handleOptionSelection = useEffectEvent((questionId: string, optionLabel: string) => {
106 if (activeQuestion?.multiSelect) {
107 onToggleOption(questionId, optionLabel);
108 return;
109 }
110 setOptimisticSingleSelect({ questionId, optionLabel });
111 onToggleOption(questionId, optionLabel);
112 if (autoAdvanceTimerRef.current !== null) {
113 window.clearTimeout(autoAdvanceTimerRef.current);
114 }
115 autoAdvanceTimerRef.current = window.setTimeout(() => {
116 autoAdvanceTimerRef.current = null;
117 onAdvanceRef.current();
118 }, 200);
119 });
120​
121 // Keyboard shortcut: number keys 1-9 select corresponding options when focus is
122 // outside editable fields. Multi-select prompts toggle options in place; single-
123 // select prompts keep the existing auto-advance behavior.
124 useEffect(() => {
125 if (!activeQuestion || responseDisabled) return;
126 const handler = (event: globalThis.KeyboardEvent) => {
127 if (event.metaKey || event.ctrlKey || event.altKey) return;
128 const target = event.target;
129 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
130 return;
131 }
132 if (
133 target instanceof HTMLElement &&
134 target.closest('[contenteditable]:not([contenteditable="false"])')
135 ) {
136 return;
137 }
138 const digit = Number.parseInt(event.key, 10);
139 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
140 const optionIndex = digit - 1;
141 if (optionIndex >= activeQuestion.options.length) return;
142 const option = activeQuestion.options[optionIndex];
143 if (!option) return;
144 event.preventDefault();
145 handleOptionSelection(activeQuestion.id, option.label);
146 };
147 document.addEventListener("keydown", handler);
148 return () => document.removeEventListener("keydown", handler);
149 }, [activeQuestion, responseDisabled]);
150​
151 if (!activeQuestion) {
152 return null;
153 }
154​
155 const customAnswerActive = progress.customAnswer.trim().length > 0;
156​
157 return (
158 <div className="px-4 py-3 sm:px-5">
159 <div className="mb-2 flex items-center gap-3">
160 <span className="text-[11px] font-semibold tracking-widest text-muted-foreground/55 uppercase">
161 {activeQuestion.header}
162 </span>
163 {prompt.questions.length > 1 ? (
164 <span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-[10px] font-medium tabular-nums text-muted-foreground/60">
165 {questionIndex + 1}/{prompt.questions.length}
166 </span>
167 ) : null}
168 </div>
169 <p className="text-sm text-foreground/90">{activeQuestion.question}</p>
170 {!canRespond ? (
171 <p className="mt-1 text-xs text-muted-foreground">
172 This request belonged to a provider process that is no longer available. Interrupt or
173 restart the run to continue.
174 </p>
175 ) : null}
176 {activeQuestion.multiSelect ? (
177 <p className="mt-1 text-xs text-muted-foreground/65">Select one or more options.</p>
178 ) : null}
179 <div className="mt-3 space-y-1.5">
180 {activeQuestion.options.map((option, index) => {
181 const isOptimisticallySelected =
182 optimisticSingleSelect?.questionId === activeQuestion.id &&
183 optimisticSingleSelect.optionLabel === option.label;
184 const isSelected =
185 isOptimisticallySelected ||
186 (!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
187 const shortcutKey = index < 9 ? index + 1 : null;
188 const className = cn(
189 "group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-all duration-150 focus-visible:border-primary/40 focus-visible:ring-1 focus-visible:ring-primary/25",
190 isSelected
191 ? "border-primary/30 bg-primary/8 text-foreground"
192 : "border-transparent bg-muted/22 text-foreground/85 hover:border-border/45 hover:bg-muted/34",
193 responseDisabled && "opacity-50 cursor-not-allowed",
194 !responseDisabled && "cursor-pointer",
195 );
196 const content = (
197 <>
198 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
199 <span className="text-sm font-medium">{option.label}</span>
200 {option.description && option.description !== option.label ? (
201 <span className="text-xs text-muted-foreground/50">{option.description}</span>
202 ) : null}
203 </div>
204 {isSelected ? (
205 <CheckIcon className="size-3.5 shrink-0 text-primary" />
206 ) : shortcutKey !== null ? (
207 <kbd
208 className={cn(
209 "flex size-5 shrink-0 items-center justify-center rounded border border-border/50 text-[11px] font-medium tabular-nums transition-colors duration-150",
210 "bg-background/35 text-muted-foreground/70 group-hover:border-border/70 group-hover:text-muted-foreground",
211 )}
212 >
213 {shortcutKey}
214 </kbd>
215 ) : null}
216 </>
217 );
218 return (
219 <button
220 key={`${activeQuestion.id}:${option.label}`}
221 type="button"
222 disabled={responseDisabled}
223 aria-disabled={responseDisabled}
224 onClick={() => {
225 if (responseDisabled) return;
226 handleOptionSelection(activeQuestion.id, option.label);
227 }}
228 className={className}
229 >
230 {content}
231 </button>
232 );
233 })}
234 </div>
235 </div>
236 );
237});