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

ComposerPendingUserInputPanel.tsx

227 lines8.1 KB

1import { type ApprovalRequestId } 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: ApprovalRequestId[];
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 autoAdvanceTimerRef = useRef<number | null>(null);
63 const onAdvanceRef = useRef(onAdvance);
64 const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
65 questionId: string;
66 optionLabel: string;
67 } | null>(null);
68​
69 useEffect(() => {
70 onAdvanceRef.current = onAdvance;
71 }, [onAdvance]);
72​
73 useEffect(() => {
74 if (!activeQuestion || activeQuestion.multiSelect || !optimisticSingleSelect) {
75 return;
76 }
77 if (optimisticSingleSelect.questionId !== activeQuestion.id) {
78 setOptimisticSingleSelect(null);
79 return;
80 }
81 if (
82 progress.customAnswer.trim().length === 0 &&
83 progress.selectedOptionLabels.includes(optimisticSingleSelect.optionLabel)
84 ) {
85 setOptimisticSingleSelect(null);
86 }
87 }, [
88 activeQuestion,
89 optimisticSingleSelect,
90 progress.customAnswer,
91 progress.selectedOptionLabels,
92 ]);
93​
94 // Clear auto-advance timer on unmount
95 useEffect(() => {
96 return () => {
97 if (autoAdvanceTimerRef.current !== null) {
98 window.clearTimeout(autoAdvanceTimerRef.current);
99 }
100 };
101 }, []);
102​
103 const handleOptionSelection = useEffectEvent((questionId: string, optionLabel: string) => {
104 if (activeQuestion?.multiSelect) {
105 onToggleOption(questionId, optionLabel);
106 return;
107 }
108 setOptimisticSingleSelect({ questionId, optionLabel });
109 onToggleOption(questionId, optionLabel);
110 if (autoAdvanceTimerRef.current !== null) {
111 window.clearTimeout(autoAdvanceTimerRef.current);
112 }
113 autoAdvanceTimerRef.current = window.setTimeout(() => {
114 autoAdvanceTimerRef.current = null;
115 onAdvanceRef.current();
116 }, 200);
117 });
118​
119 // Keyboard shortcut: number keys 1-9 select corresponding options when focus is
120 // outside editable fields. Multi-select prompts toggle options in place; single-
121 // select prompts keep the existing auto-advance behavior.
122 useEffect(() => {
123 if (!activeQuestion || isResponding) return;
124 const handler = (event: globalThis.KeyboardEvent) => {
125 if (event.metaKey || event.ctrlKey || event.altKey) return;
126 const target = event.target;
127 if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
128 return;
129 }
130 if (
131 target instanceof HTMLElement &&
132 target.closest('[contenteditable]:not([contenteditable="false"])')
133 ) {
134 return;
135 }
136 const digit = Number.parseInt(event.key, 10);
137 if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
138 const optionIndex = digit - 1;
139 if (optionIndex >= activeQuestion.options.length) return;
140 const option = activeQuestion.options[optionIndex];
141 if (!option) return;
142 event.preventDefault();
143 handleOptionSelection(activeQuestion.id, option.label);
144 };
145 document.addEventListener("keydown", handler);
146 return () => document.removeEventListener("keydown", handler);
147 }, [activeQuestion, isResponding]);
148​
149 if (!activeQuestion) {
150 return null;
151 }
152​
153 const customAnswerActive = progress.customAnswer.trim().length > 0;
154​
155 return (
156 <div className="px-4 py-3 sm:px-5">
157 <div className="mb-2 flex items-center gap-3">
158 <span className="text-[11px] font-semibold tracking-widest text-muted-foreground/55 uppercase">
159 {activeQuestion.header}
160 </span>
161 {prompt.questions.length > 1 ? (
162 <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">
163 {questionIndex + 1}/{prompt.questions.length}
164 </span>
165 ) : null}
166 </div>
167 <p className="text-sm text-foreground/90">{activeQuestion.question}</p>
168 {activeQuestion.multiSelect ? (
169 <p className="mt-1 text-xs text-muted-foreground/65">Select one or more options.</p>
170 ) : null}
171 <div className="mt-3 space-y-1.5">
172 {activeQuestion.options.map((option, index) => {
173 const isOptimisticallySelected =
174 optimisticSingleSelect?.questionId === activeQuestion.id &&
175 optimisticSingleSelect.optionLabel === option.label;
176 const isSelected =
177 isOptimisticallySelected ||
178 (!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
179 const shortcutKey = index < 9 ? index + 1 : null;
180 const className = cn(
181 "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",
182 isSelected
183 ? "border-primary/30 bg-primary/8 text-foreground"
184 : "border-transparent bg-muted/22 text-foreground/85 hover:border-border/45 hover:bg-muted/34",
185 isResponding && "opacity-50 cursor-not-allowed",
186 !isResponding && "cursor-pointer",
187 );
188 const content = (
189 <>
190 <div className="min-w-0 flex-1 flex flex-col gap-0.5">
191 <span className="text-sm font-medium">{option.label}</span>
192 {option.description && option.description !== option.label ? (
193 <span className="text-xs text-muted-foreground/50">{option.description}</span>
194 ) : null}
195 </div>
196 {isSelected ? (
197 <CheckIcon className="size-3.5 shrink-0 text-primary" />
198 ) : shortcutKey !== null ? (
199 <kbd
200 className={cn(
201 "flex size-5 shrink-0 items-center justify-center rounded border border-border/50 text-[11px] font-medium tabular-nums transition-colors duration-150",
202 "bg-background/35 text-muted-foreground/70 group-hover:border-border/70 group-hover:text-muted-foreground",
203 )}
204 >
205 {shortcutKey}
206 </kbd>
207 ) : null}
208 </>
209 );
210 return (
211 <button
212 key={`${activeQuestion.id}:${option.label}`}
213 type="button"
214 disabled={isResponding}
215 onClick={() => {
216 handleOptionSelection(activeQuestion.id, option.label);
217 }}
218 className={className}
219 >
220 {content}
221 </button>
222 );
223 })}
224 </div>
225 </div>
226 );
227});