-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathAskUserQuestionPrompt.tsx
More file actions
274 lines (245 loc) · 7.85 KB
/
AskUserQuestionPrompt.tsx
File metadata and controls
274 lines (245 loc) · 7.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import React, { useEffect, useMemo, useState } from "react";
import { Box, Text } from "ink";
import type { AskUserQuestionAnswers, AskUserQuestionItem } from "./askUserQuestion";
import { useTerminalInput } from "./PromptInput";
type Props = {
questions: AskUserQuestionItem[];
onSubmit: (answers: AskUserQuestionAnswers) => void;
onCancel: () => void;
};
const OTHER_VALUE = "__other__";
type OptionEntry = {
label: string;
description?: string;
value: string;
isOther?: boolean;
};
export function AskUserQuestionPrompt({ questions, onSubmit, onCancel }: Props): React.ReactElement | null {
const [questionIndex, setQuestionIndex] = useState(0);
const [cursorIndex, setCursorIndex] = useState(0);
const [answers, setAnswers] = useState<AskUserQuestionAnswers>({});
const [selectedValues, setSelectedValues] = useState<Record<number, string[]>>({});
const [otherTexts, setOtherTexts] = useState<Record<number, string>>({});
const [statusMessage, setStatusMessage] = useState<string | null>(null);
const question = questions[questionIndex];
const options = useMemo(() => buildOptions(question), [question]);
const selectedForQuestion = selectedValues[questionIndex] ?? [];
const otherText = otherTexts[questionIndex] ?? "";
const isCurrentOther = options[cursorIndex]?.isOther === true;
useEffect(() => {
if (!statusMessage) {
return;
}
const timer = setTimeout(() => setStatusMessage(null), 2500);
return () => clearTimeout(timer);
}, [statusMessage]);
useEffect(() => {
setQuestionIndex(0);
setCursorIndex(0);
setAnswers({});
setSelectedValues({});
setOtherTexts({});
setStatusMessage(null);
}, [questions]);
useEffect(() => {
if (cursorIndex >= options.length) {
setCursorIndex(Math.max(0, options.length - 1));
}
}, [cursorIndex, options.length]);
useTerminalInput((input, key) => {
if (!question) {
return;
}
if (key.escape) {
onCancel();
return;
}
if (key.ctrl && (input === "c" || input === "C")) {
onCancel();
return;
}
if (key.upArrow) {
setCursorIndex((index) => Math.max(0, index - 1));
return;
}
if (key.downArrow) {
setCursorIndex((index) => Math.min(options.length - 1, index + 1));
return;
}
if (key.backspace && isCurrentOther) {
setOtherTexts((prev) => ({
...prev,
[questionIndex]: (prev[questionIndex] ?? "").slice(0, -1),
}));
return;
}
if (key.return) {
commitCurrentQuestion();
return;
}
if (isCurrentOther && input && !key.ctrl && !key.meta && !input.startsWith("\u001B")) {
const sanitized = input.replace(/\r/g, "");
if (sanitized) {
setOtherTexts((prev) => ({
...prev,
[questionIndex]: `${prev[questionIndex] ?? ""}${sanitized}`,
}));
}
return;
}
if (question.multiSelect && input === " " && !key.ctrl && !key.meta) {
toggleCurrentOption();
return;
}
if (question.multiSelect && input && /^[1-9]$/.test(input)) {
const nextIndex = Number(input) - 1;
if (nextIndex >= 0 && nextIndex < options.length) {
toggleOption(options[nextIndex]?.value ?? "");
}
}
});
if (!question) {
return null;
}
function toggleCurrentOption(): void {
const value = options[cursorIndex]?.value;
if (value) {
toggleOption(value);
}
}
function toggleOption(value: string): void {
setSelectedValues((prev) => {
const current = prev[questionIndex] ?? [];
const next = current.includes(value) ? current.filter((item) => item !== value) : [...current, value];
return { ...prev, [questionIndex]: next };
});
}
function commitCurrentQuestion(): void {
const answer = buildAnswerForQuestion(question, options[cursorIndex], selectedForQuestion, otherText);
if (!answer) {
setStatusMessage(
question.multiSelect
? "Select at least one option with Space, or type an Other answer."
: "Select an option, or type an Other answer."
);
return;
}
const nextAnswers = {
...answers,
[question.question]: answer,
};
setAnswers(nextAnswers);
if (questionIndex >= questions.length - 1) {
onSubmit(nextAnswers);
return;
}
setQuestionIndex((index) => index + 1);
setCursorIndex(0);
}
return (
<Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1} marginY={1}>
<Box marginBottom={1}>
<Text color="yellow" bold>
Answer questions
</Text>
<Text dimColor>
{" "}
{questionIndex + 1}/{questions.length}
</Text>
</Box>
<Text bold>{question.question}</Text>
<Box flexDirection="column" marginTop={1}>
{options.map((option, index) => {
const isCursor = index === cursorIndex;
const isSelected = option.isOther
? selectedForQuestion.includes(OTHER_VALUE) || Boolean(otherText.trim())
: selectedForQuestion.includes(option.value) || answers[question.question] === option.label;
const marker = question.multiSelect ? (isSelected ? "[x]" : "[ ]") : isSelected ? "●" : "○";
return (
<Box key={option.value} flexDirection="column">
<Text color={isCursor ? "cyanBright" : undefined}>
{isCursor ? "> " : " "}
{marker} <Text bold={isCursor}>{option.label}</Text>
</Text>
{option.isOther ? (
<Box
marginLeft={4}
marginTop={0}
borderStyle="single"
borderColor={isCursor ? "cyanBright" : "gray"}
paddingX={1}
width={64}
>
{otherText ? (
<Text color="white">
{otherText}
{isCursor ? <Text color="cyanBright">▌</Text> : null}
</Text>
) : (
<Text dimColor>{isCursor ? "type your answer here" : "type a custom answer"}</Text>
)}
</Box>
) : null}
{option.description ? <Text dimColor> {option.description}</Text> : null}
</Box>
);
})}
</Box>
<Box marginTop={1}>
<Text dimColor>
{statusMessage ??
(isCurrentOther
? "Type your answer · Backspace edit · Enter submit/next · ↑ choose presets · Esc type manually"
: question.multiSelect
? "↑/↓ move · Space toggle · Enter submit/next · Esc type manually"
: "↑/↓ move · Enter select/next · Esc type manually")}
</Text>
</Box>
</Box>
);
}
function buildOptions(question: AskUserQuestionItem | undefined): OptionEntry[] {
if (!question) {
return [];
}
return [
...question.options.map((option) => ({
label: option.label,
description: option.description,
value: option.label,
})),
{
label: "Other",
value: OTHER_VALUE,
isOther: true,
},
];
}
function buildAnswerForQuestion(
question: AskUserQuestionItem,
focusedOption: OptionEntry | undefined,
selectedValues: string[],
otherText: string
): string | null {
const trimmedOther = otherText.trim();
if (question.multiSelect) {
const labels = selectedValues
.filter((value) => value !== OTHER_VALUE)
.map((value) => value.trim())
.filter(Boolean);
if (selectedValues.includes(OTHER_VALUE) && !trimmedOther) {
return null;
}
if (trimmedOther) {
labels.push(trimmedOther);
}
return labels.length > 0 ? labels.join(", ") : null;
}
if (!focusedOption) {
return null;
}
if (focusedOption.isOther) {
return trimmedOther || null;
}
return focusedOption.label;
}